Swift Control Transfer

Control transfer statements change the normal top-to-bottom order of execution. A program usually runs one line after another. Control transfer keywords let the program leave a loop early, skip an item, jump into another case, or exit a function.

Road signs give a good picture. A stop sign ends the trip, a detour sign skips a section of road, and an exit sign leaves the highway. Swift offers five keywords with similar jobs: break, continue, fallthrough, return, and throw.

Diagram: Road Signs of Swift

 Loop body:  [1] -> [2] -> [3] -> [4] -> [5]

 break     :  [1] -> [2] -> [3] -X   (loop ends completely)
 continue  :  [1] -> [2] -> skip 3 -> [4] -> [5]
 return    :  leaves the whole function
 throw     :  leaves the function and reports an error

The Break Statement

The break keyword ends the nearest loop or switch immediately. Execution continues at the line after the loop.

for number in 1...10 {
    if number == 5 {
        break
    }
    print(number)
}
// Output: 1 2 3 4

Break fits search tasks. A program that looks for one name in a list can stop the moment it finds a match.

The Continue Statement

The continue keyword skips the rest of the current loop round and starts another round. The loop keeps running.

for number in 1...6 {
    if number % 2 == 0 {
        continue
    }
    print(number)
}
// Output: 1 3 5

Even numbers trigger continue. The print line never runs for them.

The Fallthrough Statement

A Swift switch case ends automatically after its body runs. Other languages need a break for this behavior, while Swift builds it in. The fallthrough keyword overrides the default and runs the body of the following case as well.

let grade = "B"

switch grade {
case "A":
    print("Excellent")
case "B":
    print("Good")
    fallthrough
case "C":
    print("Pass")
default:
    print("Needs work")
}
// Output:
// Good
// Pass

Fallthrough ignores the condition of the following case and runs that body. Use it rarely and comment the reason.

The Return Statement

A return statement ends a function and optionally sends a value to the caller.

func firstNegative(in numbers: [Int]) -> Int? {
    for number in numbers {
        if number < 0 {
            return number
        }
    }
    return nil
}

print(firstNegative(in: [4, 7, -2, 9]) ?? 0)   // Output: -2

The function leaves the loop and the function together once it finds a negative number.

Labeled Statements

A plain break affects only the nearest loop. A label gives a loop a name, and the break statement can target that name. Labels help with nested loops.

outer: for row in 1...3 {
    for column in 1...3 {
        if row * column == 4 {
            break outer
        }
        print("\(row)x\(column)")
    }
}
// Output:
// 1x1
// 1x2
// 1x3
// 2x1

The product of row 2 and column 2 equals 4. The statement break outer ends both loops together. The same label works with continue to skip a round of the outer loop.

Example: Finding a Locker

A school has lockers numbered 1 to 50. A caretaker skips broken lockers and stops at the earliest free one.

let broken = [3, 7, 12]
let occupied = [1, 2, 4, 5, 6, 8]

for locker in 1...50 {
    if broken.contains(locker) { continue }
    if occupied.contains(locker) { continue }
    print("Free locker: \(locker)")
    break
}
// Output: Free locker: 9

Common Mistakes

A break inside an if statement that sits outside any loop or switch triggers a compile error. Swift accepts break only inside a loop, a switch, or a labeled statement.

Developers sometimes place continue after the code they meant to skip. The order matters. Put the continue line above the work that should not run for that item.

Real-World Use

Login screens use return to stop a function after a failed check. Search features use break to stop at the first match. Import tools use continue to skip damaged rows in a file and keep processing the healthy rows.

Choosing the Right Keyword

Ask one question to pick the correct keyword: what should happen to the work that remains? Stop all remaining rounds and the answer is break. Skip only the current round and the answer is continue. Leave the entire function and the answer is return. Report a problem to the caller and the answer is throw.

Readable code uses these keywords sparingly. A loop with five different exits becomes difficult to follow. Split the loop body into a small function when the exits multiply.

Key Takeaways

  • break ends a loop or switch.
  • continue skips the rest of one loop round.
  • fallthrough runs the following switch case body.
  • return and throw leave a function.
  • Labels let break and continue target an outer loop.