Loops in Swift
for-in and while loops, and the control statements that shape how they run.
2 min de lectura
Swift has two loop forms you'll use constantly: for-in, for iterating over a known sequence, and while, for repeating until a condition changes.
for-in
for i in 1...5 {
print(i) // 1, 2, 3, 4, 5
}
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print(fruit)
}
let scores = ["Ada": 95, "Sam": 88]
for (name, score) in scores {
print("\(name): \(score)")
}for-in works over ranges, arrays, dictionaries, and anything else that conforms to Swift's Sequence protocol (covered more in the protocols lesson later). When you don't need the loop variable at all — just the number of repetitions — replace it with _:
for _ in 1...3 {
print("Hi") // prints "Hi" three times
}That underscore is a small but common idiom: it tells the reader (and the compiler) "this value is intentionally unused."
while and repeat-while
while checks its condition before each iteration:
var countdown = 3
while countdown > 0 {
print(countdown)
countdown -= 1
}
print("Liftoff!")repeat-while (Swift's version of do-while) checks the condition after running the body, so the body always executes at least once:
var attempts = 0
repeat {
attempts += 1
print("Attempt \(attempts)")
} while attempts < 3Use repeat-while specifically when the loop body needs to run once before there's anything meaningful to check — like reading a first line of input before deciding whether to keep reading.
Controlling loop flow
break exits a loop immediately; continue skips to the next iteration:
for number in 1...10 {
if number % 2 != 0 {
continue // skip odd numbers
}
if number > 6 {
break // stop once we pass 6
}
print(number) // prints 2, 4, 6
}Labeled loops
When loops are nested, a plain break or continue only affects the innermost loop. A label lets you target an outer loop directly:
outerLoop: for row in 1...3 {
for column in 1...3 {
if row == 2 && column == 2 {
break outerLoop // exits BOTH loops, not just the inner one
}
print("(\(row), \(column))")
}
}Without the label, break here would only stop the inner loop and let the outer one keep going. Labeled loops come up rarely, but they're the cleanest way to escape deeply nested iteration without resorting to extra flag variables.