In swift for loop, you can get the value of iterator usually named “i” in the following way
let pets = ["🦮","🐕🦺","🐩","🦄","🐮"] for (i,pet) in pets.enumerated() { // we enumerated through the pets array and got a tuple with iterator and value print("\(pet) at index \(i)") } //OUTPUT 🦮 at index 0 🐕🦺 at index 1 🐩 at index 2 🦄 at index 3 🐮 at index 4
In order to get the iterator, we enumerated through the array and decomposed the tuple in i and value. Decomposing individual element when we enumerate in swift for loop is not entirely necessary as the below code will show
for a in pets.enumerated() { print("\(a.1) at index \(a.0)") } //OUTPUT 🦮 at index 0 🐕🦺 at index 1 🐩 at index 2 🦄 at index 3 🐮 at index 4
Other ways to use swift for loop
For loop in swift using range
We can use a range and iterate over it using for loop as shown in the code below
let ourRange = 1...6 for i in ourRange { print(i) }
For loop in swift on a iterable collection
We can iterate over a collection easily using for loop in swift as shown in the code below
let pets = ["🦮","🐕🦺","🐩","🦄","🐮"] for pet in pets { print(pet) }
It is not always necessary to use the element of collection we can ignore it by using underscore in swift for loop
let pets = ["🦮","🐕🦺","🐩","🦄","🐮"] for _ in pets { print("All are mine") }
Hope this helps!!!