Swift For Loop

Swift For-In Loop

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.


Iterating Over Arrays

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.

Looping through an Array:

let fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits { print("I love \(fruit)") }


Iterating Over Ranges

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.

Looping over a Range:

for number in 1...5 {
    print("\(number) times 5 is \(number * 5)")
}

The Underscore _ Variable

Sometimes, 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.

Ignoring the Loop Variable:

for _ in 1...3 {
    print("Hello!")
}

This will simply print "Hello!" three times.


Exercise

What symbol should you use in a for-in loop if you do NOT need to use the current sequence value?