Control flow
Swift loops: the while loop
Learn the while and repeat-while loops in Swift: how the condition check works, break and continue, and how to avoid the infinite loop pitfall.
8 minute lesson
This tutorial belongs to the Swift series
A while loop repeats a block of code as long as a condition stays true. Swift checks the condition before each iteration, so if the condition is false from the start, the body never runs.
Here’s the basic form:
var count = 0
while count < 3 {
print(count)
count += 1
}
// prints 0, 1, 2
Follow what happens step by step. count starts at 0, so the condition is true and the loop prints 0. Then count += 1 brings it to 1, still less than 3, so we go again. When count reaches 3, the condition becomes false and the loop ends.
And this is a loop that never runs:
var count = 10
while count < 3 {
print("never printed")
}
The condition is false at the first check, so Swift skips the body entirely.
What if you need at least one iteration?
Sometimes you want the body to run once no matter what, and check the condition after. Other languages call this a do-while loop. Swift calls it repeat-while:
var count = 10
repeat {
print(count) // 10
count += 1
} while count < 3
This prints 10 once, even though the condition was already false. The body runs first, then the condition is checked.
repeat-while is the right tool when the work itself produces the value you’re testing. Think of asking the user for input: you have to ask at least once before you can validate the answer.
A realistic example
A common pattern is processing items until there’s nothing left:
var tasks = ["email", "meeting", "code review"]
while !tasks.isEmpty {
let task = tasks.removeFirst()
print("Doing: \(task)")
}
Each iteration removes one task from the array. When the array is empty, !tasks.isEmpty is false and the loop stops. The loop condition and the work inside are connected, which is exactly what you want.
break and continue
break exits the loop immediately, skipping any remaining iterations:
var number = 0
while number < 10 {
number += 1
if number == 5 {
break
}
print(number) // 1, 2, 3, 4
}
continue skips the rest of the current iteration and jumps back to the condition check:
var number = 0
while number < 6 {
number += 1
if number % 2 == 0 {
continue
}
print(number) // 1, 3, 5
}
Here every even number gets skipped, because continue jumps over the print() call.
The infinite loop pitfall
The most common while bug is forgetting to change the variable used in the condition:
var count = 0
while count < 3 {
print(count)
// we forgot count += 1
}
count stays at 0 forever, so the condition never becomes false. This loop prints 0 until you kill the program.
My advice: every time you write a while loop, ask yourself “what makes this condition become false?” before you write the body. If you can’t answer, the loop will never end.
Lesson completed