0Pricing
Swift Academy · Lesson

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

  1. break and continue Basics
  2. Labeled Statements
  3. Breaking Out of Nested Loops
  4. Loop Control in switch Context
← Back to Swift Academy