The for-in loop is the primary tool for iterating over sequences, such as arrays, ranges, and strings.
It is clean, safe, and heavily eliminates the off-by-one errors common in traditional for(int i=0; i<length; i++) loops found in C-style languages.
You can easily loop through every item inside an array using for-in.
Swift automatically pulls each item out of the collection and assigns it to a temporary constant that you can use inside the loop.
let fruits = ["Apple", "Banana", "Cherry"]for fruit in fruits { print("I love \(fruit)") }
If you simply want to execute a block of code a specific number of times, you can combine a for-in loop with a numeric range.
for number in 1...5 {
print("\(number) times 5 is \(number * 5)")
}
_ VariableSometimes, you need to loop a certain number of times, but you don't actually need to use the loop variable (like number in the example above).
In Swift, you can use an underscore _ in place of a variable name to ignore the value. This improves performance and makes your intention clear.
for _ in 1...3 {
print("Hello!")
}
This will simply print "Hello!" three times.
What symbol should you use in a for-in loop if you do NOT need to use the current sequence value?