Swift Loops Control Transfer Statements
By Flavio Copes
Learn how to use the continue and break statements in Swift to control the flow inside a loop, skipping an iteration or ending the loop early.
This tutorial belongs to the Swift series
Swift provides you 2 statements that you can use to control the flow inside a loop: continue and break.
continue is used to stop the current iteration, and run the next iteration of the loop.
break ends the loop, not executing any other iteration.
Skipping iterations with continue
Say we have a list of grades and we only want to print the passing ones. When we find a grade below 6, we skip it and move on:
let grades = [8, 4, 9, 6, 3]
for grade in grades {
if grade < 6 {
continue
}
print(grade)
}
// 8
// 9
// 6
The loop still visits every item. continue just jumps straight to the next one, skipping the rest of the body for the current item.
Ending the loop with break
break is more drastic. As soon as it runs, the whole loop is over:
let list = ["a", "b", "c"]
for item in list {
if item == "b" {
break
}
print(item)
}
// a
Only "a" is printed. When the loop reaches "b", break ends it, and "c" is never visited.
This is useful when you’re searching for something: once you found it, there’s no reason to keep looping.
Breaking out of nested loops
By default, break only ends the innermost loop it lives in. If you have a loop inside a loop and you want to end both, give the outer loop a label and break to it:
outer: for row in 1...3 {
for column in 1...3 {
if row * column > 4 {
break outer
}
print(row, column)
}
}
When row * column goes over 4, break outer ends both loops at once. Without the label, only the inner loop would end, and the outer one would keep going with the next row.
The same labels work with continue too, to jump to the next iteration of the outer loop.
A common pitfall with switch
Be careful when a switch statement sits inside a loop. In Swift, break inside a switch ends the switch, not the loop. If you want to end the loop from inside a switch case, label the loop and use break with that label, like we did above.
Related posts about swift: