← Back to Swift Course | Chapter 3: Control Flow | Lesson 6 of 8

break and continue

break stops a loop completely, while continue just skips the rest of the current lap and moves to the next one.
Syntax
swift
for item in collection {
    if condition { break }      // leave the loop
    if condition { continue }   // skip to next item
}

label: for a in outer {
    for b in inner { continue label }
}

Using break to Exit Early

break immediately stops the loop entirely, skipping any remaining iterations.

Example: Using break to Exit Early

markup
// Loop over `1...10`, binding each item to `number`
for number in 1...10 {
    // Check whether `number == 4`
    if number == 4 {
        break
    }
    // Print "Number: \(number)" to the console
    print("Number: \(number)")
}

Using continue to Skip an Iteration

continue skips the rest of the current iteration's code and jumps straight to the next one, without stopping the loop entirely.

Example: Using continue to Skip an Iteration

markup
// Loop over `1...6`, binding each item to `number`
for number in 1...6 {
    // Check whether `number % 2 == 0`
    if number % 2 == 0 {
        continue
    }
    // Print "Odd number: \(number)" to the console
    print("Odd number: \(number)")
}

Labeled Loops

A label placed before a loop lets break or continue target that specific loop even from inside a nested loop.

Example: Labeled Loops

markup
outer: for i in 1...3 {
    // Loop over `1...3`, binding each item to `j`
    for j in 1...3 {
        // Check whether `j == 2`
        if j == 2 {
            continue outer
        }
        // Print "i=\(i), j=\(j)" to the console
        print("i=\(i), j=\(j)")
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using break when the intent was only to skip the current iteration; that requires continue, not break.
  2. Forgetting that break inside a switch exits the switch itself, not an enclosing loop -- use a labeled break for that case.
  3. Placing code after a continue in the same iteration expecting it to still run; nothing after continue executes for that pass.
Chapter Summary
  • break immediately exits the nearest enclosing loop (or switch).
  • continue skips the rest of the current iteration and moves to the next one.
  • Labeled loops (outerLoop: for ...) let break or continue target a specific outer loop.
  • Both are commonly combined with an if condition to control loop flow.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.