Swift Loops
Loops repeat a block of code. Swift has three kinds:
| Loop | Use it when… |
|---|---|
for-in |
you iterate over a range, an array, a string or any other sequence |
while |
you repeat as long as a condition is true, checking it before each pass |
repeat-while |
like while, but the condition is checked after each pass, so the body runs at least once |
There is no C-style for (i = 0; i < n; i++) loop in Swift — ranges and sequences replace it.
for-in with ranges
a...b is a closed range (includes b), a..<b is a half-open range (stops before b):
for i in 1...3 {
print("Closed range: \(i)")
}
for i in 0..<3 {
print("Half-open range: \(i)")
}Closed range: 1
Closed range: 2
Closed range: 3
Half-open range: 0
Half-open range: 1
Half-open range: 2
Tip:
0..<array.countis the classic way to loop over indices, but usually you can loop over the elements directly — or usearray.indices.
for-in over collections and strings
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print("I like \(fruit)")
}
for (index, fruit) in fruits.enumerated() {
print("\(index + 1). \(fruit)")
}
for letter in "Swift" {
print(letter, terminator: " ")
}
print()I like apple
I like banana
I like cherry
1. apple
2. banana
3. cherry
S w i f t
enumerated() gives you (offset, element) pairs, which you can unpack into two names right in the loop header.
Stepping and counting backwards
Use stride to jump by a step other than 1, and reversed() to count down. If you don't need the loop variable, name it _:
for even in stride(from: 0, through: 10, by: 2) {
print(even, terminator: " ")
}
print()
for n in (1...5).reversed() {
print(n, terminator: "… ")
}
print("Liftoff! 🚀")
for _ in 1...3 {
print("Hip hip hooray!")
}0 2 4 6 8 10
5… 4… 3… 2… 1… Liftoff! 🚀
Hip hip hooray!
Hip hip hooray!
Hip hip hooray!
stride(from:to:by:) excludes the end value, stride(from:through:by:) includes it.
while
A while loop checks its condition first. If the condition is false from the start, the body never runs:
var balance = 100
var month = 0
while balance > 0 {
month += 1
balance -= 30
print("Month \(month): balance \(balance)")
}
print("Money ran out after \(month) months.")Month 1: balance 70
Month 2: balance 40
Month 3: balance 10
Month 4: balance -20
Money ran out after 4 months.
repeat-while
repeat { … } while condition runs the body once before checking. It's Swift's version of do-while from other languages:
var attempts = 0
var guess = 10
repeat {
attempts += 1
guess -= 4
print("Attempt \(attempts): guess is \(guess)")
} while guess > 0
var neverTrue = false
repeat {
print("This line runs once even though the condition is false.")
} while neverTrueAttempt 1: guess is 6
Attempt 2: guess is 2
Attempt 3: guess is -2
This line runs once even though the condition is false.
Nested loops
Loops can contain other loops. A small multiplication table:
for row in 1...3 {
var line = ""
for col in 1...4 {
line += "\(row * col)\t"
}
print(line)
}1 2 3 4
2 4 6 8
3 6 9 12
Note: A
whileloop whose condition never becomes false runs forever. In a playground that means a timeout — always make sure something inside the loop moves you toward the end.
Test yourself
How many times does for i in 0..<5 { } run?
- 4
- 5
- 6
- 0
Which loop always executes its body at least once?
- for-in
- while
- repeat-while
- None of them
What does stride(from: 10, to: 0, by: -5) produce?
- 10, 5, 0
- 10, 5
- 0, 5, 10
- 5, 0