while and repeat-while Loops
Prerequisites: for-in loops and ranges
A while loop repeats as long as its condition stays true. Use it when
you don't know in advance how many times to loop.
Real-world analogy: "While the kettle isn't boiling, keep waiting."
while
var balance = 100
var months = 0
while balance < 200 {
balance += balance / 10
months += 1
}
print("Doubled after \(months) months: \(balance)")
Doubled after 8 months: 212
The condition is checked before each pass. If it's false from the start, the loop body never runs.
repeat-while
repeat { } while condition checks after each pass, so the body
always runs at least once — ideal for "ask until the answer is valid":
var attempts = 0
repeat {
attempts += 1
print("Attempt \(attempts)")
} while attempts < 3
Attempt 1
Attempt 2
Attempt 3
Common mistakes
- Forgetting to change the variable in the condition, so the loop never ends. Stop a runaway program with Ctrl + C.
- Using
whileto walk through an array with a counter.for-inis clearer and can't go out of range.
Practice
Starting from 1, keep doubling a number while it's below 1,000, then print the first value that reached 1,000 or more.
Show solution
var n = 1
while n < 1000 {
n *= 2
}
print(n)
1024