← thecodex.expert · The Codex Family of Knowledge
Swift

Control Flow

Swift’s switch must cover every possible case, verified by the compiler — and unlike C’s notorious fall-through-by-default footgun, each case here stops automatically, with no break needed at all.

Swift 6 switch is exhaustive, no fall-through Last verified:
Canonical Definition

if/else, for-in, and while follow familiar syntax, though Swift requires parentheses around the condition only optionally (they're legal but not required, unlike C). switch is where Swift genuinely departs from its C-family ancestors: the compiler VERIFIES every possible case is covered (an enum switch missing a case is a compile error, not a silent bug), and each case stops automatically with no fall-through to the next one — the classic missing-break bug simply cannot happen. guard provides an early-exit pattern: its condition must be true to continue, and the else block is required to exit the current scope (return, break, or similar), making a function's validation logic read top-to-bottom instead of nesting deeply.

switch: exhaustive, and no fall-through by default

Missing a case for .charging here is a COMPILE ERROR — the compiler verified every enum case is handled. And unlike C's switch, execution stops automatically after each case; there's no missing-break bug possible at all.

Swiftswitch_basics.swift
enum BatteryState {
    case full, charging, low
}

let state = BatteryState.charging

switch state {
case .full:
    print("Fully charged")
case .charging:
    print("Charging")
case .low:
    print("Low battery")
    // no break needed — falls through is NOT the default behavior here
}
// omitting .low above would be a COMPILE ERROR: switch must be exhaustive

guard: early exit, readable validation

The else block is REQUIRED to exit the current scope — the compiler enforces this, since guard's entire purpose is guaranteeing execution never continues past it without either the condition being true or the function having already exited.

Swiftguard_basics.swift
func process(age: Int) {
    guard age >= 18 else {
        print("Must be an adult")
        return   // REQUIRED — guard's else must exit the scope
    }
    // age is guaranteed >= 18 from this point onward
    print("Processing for age \(age)")
}

for-in over ranges and collections

1...5 is inclusive of both ends; 1..<5 excludes the upper bound — the exact same distinction Kotlin makes with its own range syntax, useful for avoiding off-by-one mistakes.

Swiftfor_in_loops.swift
for i in 1...5 {          // inclusive: 1, 2, 3, 4, 5
    print(i)
}

for i in 1..<5 {          // exclusive of 5: 1, 2, 3, 4
    print(i)
}

for name in ["Alice", "Bob"] {
    print(name)
}

Sources

1
Apple / Swift.org. The Swift Programming Language, "Control Flow," docs.swift.org/swift-book.