How to Loop Through an Array from the Second Element in Elegant Way Using Swift

Swift - Smart way to cycle through an Array of Array [[Int]]

You can do it this way:

let result = array.map { subarray in
subarray.map { integer -> Int in
if integer == 2 {
return 1
} else {
return integer
}
}
}

Even shorter:

let result = array.map {
$0.map { integer in
return integer == 2 ? 1 : integer
}
}

And a one-liner:

let result = array.map { $0.map { $0 == 2 ? 1 : $0 } }

I'll try to explain what's happening here in simple words: What map does is that it goes through the array elements one by one and applies a function on the element.

In our example, the first map iterates over the outer array elements, so $0 here refers to the inner arrays (one after one).

The second map iterates over the inner arrays' elements. So $0 in the inner map refers to the each element of the inner arrays' elements.

How to loop through two arrays with different amount of items? Swift

You can simply do,

var i = 0
for _ in 0..<min(alienArray.count, humanArray.count) {
print(humanArray[i].name, alienArray[i].numberOfLegs)
i += 1
}
print(humanArray[i...].compactMap({ $0.name }).joined(separator: " "))
print(alienArray[i...].compactMap({ $0.numberOfLegs }).joined(separator: " "))

How to iterate through multiple UILabels

You could put your labels inside another array and iterate through them:

let labelsArray = [positionTouch1LBL, positionTouch2LBL, positionTouch3LBL, positionTouch4BL, positionTouch5LBL]

for i in 0..<labelsArray.count {
// Get i-th UILabel
let label = labelsArray[i]
if touches.count >= (i+1) {
label.text = String(describing: touches[i].location(in: view))
}else{
label.text = "0.0 / 0.0"
}
}

This way you are able to group redundant code

How to loop through an optional collection

You have a couple of options. You can provide an empty array as the default value for elements in a for ... in loop:

let elements: [Element]?

for element in elements ?? [] {

}

Or you can use forEach and optional chaining on elements

elements?.forEach { element in

}

Bear in mind that optional collections are an anti-pattern in Swift. You can represent the lack of value using an empty collection, so wrapping a collection in an optional doesn't provide any extra value, while complicating the interface.



Related Topics



Leave a reply



Submit