Lesson 18Control Flow

Break & Continue

Controlling Loop Flow

Sometimes you need to exit a loop early or skip certain iterations. break and continue give you that control!

Break vs Continue

break

Exits the loop completely

🛑STOP - No more iterations

continue

Skips current iteration only

⏭️SKIP - Go to next iteration

Visual Example

Loop: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

break at 5→ Prints: 1, 2, 3, 4
continue if even→ Prints: 1, 3, 5, 7, 9

Labeled Statements

For nested loops, use labels to specify which loop to break/continue:

outerLoop: for i in 1...3 {
  for j in 1...3 {
    break outerLoop
  }
}

When to Use

Use break for:

  • Finding first match
  • Early exit on error
  • Stopping on condition

Use continue for:

  • Skipping invalid items
  • Filtering in a loop
  • Ignoring special cases
main.swift
// BREAK - Exit the loop immediately
print("--- BREAK Example ---")

for i in 1...10 {
    if i == 5 {
        print("Found 5! Stopping.")
        break  // Exit the loop
    }
    print("Number: \(i)")
}
// Output: 1, 2, 3, 4, Found 5! Stopping.

// CONTINUE - Skip to next iteration
print("\n--- CONTINUE Example ---")

for i in 1...10 {
    if i % 2 == 0 {
        continue  // Skip even numbers
    }
    print("Odd number: \(i)")
}
// Output: 1, 3, 5, 7, 9

// Real example: Find first negative
let numbers = [5, 3, -2, 8, -1, 4]

for num in numbers {
    if num < 0 {
        print("First negative: \(num)")
        break
    }
}

// Real example: Print only positive
print("\nPositive numbers only:")
for num in numbers {
    if num < 0 {
        continue  // Skip negative
    }
    print(num)
}

// Nested loops with labeled break
print("\n--- Labeled Break ---")

outerLoop: for i in 1...3 {
    for j in 1...3 {
        if i == 2 && j == 2 {
            print("Breaking out of both loops!")
            break outerLoop
        }
        print("(\(i), \(j))")
    }
}

// Search in 2D array
let grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
let target = 5

searchLoop: for row in grid {
    for num in row {
        if num == target {
            print("Found \(target)!")
            break searchLoop
        }
    }
}

Try It Yourself!

Loop through numbers 1-20: skip multiples of 3, and stop completely when you reach a number greater than 15!