Changing the step
A while loop doesn't have to count by one. The update decides how far the variable moves, and the condition decides where the loop stops. Two variations cover most cases: a larger step and counting down.
Example 1: a step of 2
To print the even numbers from 4 through 14, start at 4 and add 2 each time:
var i = 4
while i <= 14 {
print(i)
i += 2
}
4
6
8
10
12
14
Starting on an even number and adding 2 keeps every value even. The last number printed is 14, because 14 <= 14 is true. The next value, 16, fails the condition.
Example 2: counting down
To go in reverse, start at the high end, subtract in the update and flip the comparison:
var i = 12
while i >= 4 {
print(i)
i -= 2
}
12
10
8
6
4
The condition now uses >= because the variable shrinks. A condition like i <= 4 would be false immediately, and the body would never run. The rule is that the update must move the variable toward the point where the condition fails.
Predicting the last value
Before running a loop, work out which value fails the condition, because that is the value the variable holds afterwards. In example 1 the sequence is 4, 6, 8, 10, 12, 14 and then 16, so i is 16 when the loop ends. In example 2 it is 12, 10, 8, 6, 4 and then 2, so i is 2. This also shows why the end value matters: if the step doesn't land exactly on it, the loop simply stops at the last value that still passes the condition.
The exercise
Print all the odd numbers from 23 down to 7, in decreasing order.
- Start at the top. Declare
var counter = 23. It is odd, so subtracting 2 keeps it odd. - Write the condition. The loop runs while
counter >= 7. Seven itself is odd and must be printed, so the comparison includes it. - Print the counter inside the loop.
- Subtract 2 with
counter -= 2. This moves to the previous odd number and drives the loop toward the end.
var counter = 23
while counter >= 7 {
print(counter)
counter -= 2
}
The output is 23, 21, 19, 17, 15, 13, 11, 9, 7, one per line. The next value would be 5, which fails the condition, so after the loop counter is 5.
Common mistakes
- Wrong comparison for counting down. Use
>=or>when the variable decreases. - Starting on the wrong parity. Starting at 22 would print even numbers.
- Stopping early.
counter > 7leaves out the 7. - Adding instead of subtracting. With
counter += 2the value grows, the condition stays true forever and the loop never ends. - Using
--. Swift has no decrement operator. Write-= 1or-= 2.
Key takeaways
- The update sets the step, and its sign sets the direction.
- Count down with a
>=or>condition. - Always check that the update moves toward ending the loop.
