Sometimes you need to alter the flow of a loop from within its code block.
Swift provides control transfer statements like break and continue to help you manage this.
These keywords give you precision control over when loops should skip an iteration or terminate entirely.
break StatementThe break statement immediately ends the execution of an entire loop.
As soon as Swift hits break, it jumps out of the loop and moves to the next line of code outside the loop's body.
for i in 1...10 {
if i == 5 {
print("Hit number 5, breaking the loop!")
break
}
print(i)
}
// Output: 1, 2, 3, 4, Hit number 5...
continue StatementThe continue statement stops the current iteration of the loop and tells Swift to jump back to the top and begin the next iteration.
It skips the remaining code in the loop body for that pass only.
for i in 1...5 {
if i == 3 {
continue // Skips printing 3
}
print(i)
}
// Output: 1, 2, 4, 5
Both break and continue work identically within while and repeat-while loops.
When writing an infinite while true loop, a break statement is strictly required to eventually terminate the program!
var count = 0
while true {
count += 1
if count >= 3 { break }
}
Which keyword is used to skip the rest of the current loop iteration and move to the next one?