Breaking Out of Nested Loops
Use labels to escape multiple loop levels.
The Nested Loop Problem
A plain break inside a nested loop exits only the inner loop, leaving the outer loop running.
for i in 1...3 {
for j in 1...3 {
if j == 2 { break }
print(i, j)
}
}Labeled break Solves It
Attach a label to the outer loop and use break outer to exit both loops at once.
outer: for i in 1...3 {
for j in 1...3 {
if i == 2 && j == 2 { break outer }
print(i, j)
}
}
print("escaped")All lessons in this course
- break and continue Basics
- Labeled Statements
- Breaking Out of Nested Loops
- Loop Control in switch Context