Swift For Loop
A for loop is a loop that runs its body once for each value in a sequence. The loop hands one value at a time to a loop name inside the body.
Counting with a range
The range gives the loop its values in order. Each pass prints the current number.
for number in 1...3 {
print(number)
}Walking the characters of a string
The letters print one per line in text order. Five passes print the five letters of the word.
for letter in "Swift" {
print(letter)
}Looping over a list of values
A written list gives the loop its values in written order. Each pass prints the next stored value.
for value in [4, 8, 15] {
print(value)
}Positions and values together
The loop name holds two parts at once here. Printing both shows each value beside its position number.
for (position, value) in [10, 20, 30].enumerated() {
print("\(position) \(value)")
}Building a total in a loop
A total starts at zero before the loop. Each pass adds the current value to that total.
var total = 0
for number in 1...4 {
total += number
}
print(total)Example
var sum = 0
for (position, value) in [5, 10, 15].enumerated() {
sum += value
print(position)
}
print(sum)Key points
- Each pass through the body works with the next value in the sequence.
- The word in joins the loop name to the sequence the loop walks.
- A value built up inside the body keeps its changes from one pass to the next.
- enumerated pairs each value with a position number that starts at 0.
- A loop over a string hands out one character on each pass.
In this example, the first line sets sum to 0 before the loop starts. The loop then walks the list with positions, adding 5, then 10, then 15 to sum. Each pass prints its position, so 0, 1 and 2 print in order. The last line prints sum after the loop, which is 30.
Note
The loop name is set fresh on each pass and cannot be changed inside the body.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
A total starts at 0. A loop adds 1, 2 and 3 to it in turn. What is the total after the loop?