Swift Academy · Lesson

Breaking Out of Nested Loops

Use labels to escape multiple loop levels.

Lesson 3 of 413 steps

Breaking Out of Nested Loops is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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")

Searching a 2D Grid

Labeled break is perfect for stopping a 2D search as soon as the target is found.

let grid = [[1, 2, 3], [4, 5, 6]]
var position = (-1, -1)
find: for r in 0..<grid.count {
    for c in 0..<grid[r].count {
        if grid[r][c] == 5 {
            position = (r, c)
            break find
        }
    }
}
print(position)

Without Labels: a Flag

An alternative without labels uses a boolean flag, but it is more verbose and error-prone.

var stop = false
for i in 1...3 {
    for j in 1...3 {
        if i + j == 4 { stop = true; break }
        print(i, j)
    }
    if stop { break }
}

Labels Are Cleaner

Compared to flags, labeled break expresses the intent directly and avoids extra checks after the inner loop.

outer: for i in 1...3 {
    for j in 1...3 {
        if i + j == 4 { break outer }
        print(i, j)
    }
}

Triple Nesting

Labels scale to three or more levels; target whichever loop you need to exit.

top: for a in 1...2 {
    for b in 1...2 {
        for c in 1...2 {
            if c == 2 { break top }
            print(a, b, c)
        }
    }
}

Labeled continue in Nesting

Use continue label to skip to the next iteration of an outer loop from deep inside.

rows: for r in 1...3 {
    for c in 1...3 {
        if c == 2 { continue rows }
        print(r, c)
    }
}

Combining Both

You can mix labeled break and continue in the same nested structure for fine control.

scan: for i in 1...3 {
    for j in 1...3 {
        if j == 1 { continue }
        if i == 3 { break scan }
        print(i, j)
    }
}

Early Exit Performance

Breaking out as soon as the answer is found avoids wasted iterations on large data sets.

let data = Array(1...100)
var firstBig = -1
loop: for chunk in stride(from: 0, to: data.count, by: 10) {
    for k in chunk..<min(chunk + 10, data.count) {
        if data[k] > 25 {
            firstBig = data[k]
            break loop
        }
    }
}
print(firstBig)

Returning From a Function

Inside a function, return is another clean way to exit all loops at once.

func findPair(_ target: Int) -> (Int, Int)? {
    for i in 1...5 {
        for j in 1...5 {
            if i * j == target { return (i, j) }
        }
    }
    return nil
}
print(findPair(12) ?? (-1, -1))

Choosing an Approach

Prefer labeled break for exiting nested loops in place, or return when you are inside a function and want to leave entirely.

outer: for x in 1...3 {
    for y in 1...3 {
        if x * y >= 4 { break outer }
        print(x, y)
    }
}

Quick Check

Test nested-loop control.

Recap

A plain break exits only the innermost loop. Label the outer loop and use break label to escape all levels at once, which is cleaner than a boolean flag. Inside a function, return also exits everything.

outer: for i in 1...3 {
    for j in 1...3 {
        if j == 2 { break outer }
        print(i, j)
    }
}
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Breaking Out of Nested Loops” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Breaking Out of Nested Loops”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Breaking Out of Nested Loops”?

Use labels to escape multiple loop levels. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Breaking Out of Nested Loops” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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