|

switch: Let Exhaustiveness Work for You

Every branch of a state machine accounted for, Molecules of Swift #009

A screen that displays a synchronization operation needs to make a decision for every possible state. It might show a waiting message before work starts, progress while files transfer, an error when something fails, and a completion message at the end. These states are related, but they do not mean the same thing. Representing them as cases of one Swift enum makes that difference explicit.

A local check such as if case .failed is useful when we only care about an error. But it is not enough for a screen that promises to represent the whole operation. If the model later gains a paused state, a screen that silently ignores it may show the wrong information.

Swift’s switch solves more than the immediate branching problem. For an enum whose cases are known to the compiler, it can check whether our decision covers every possible case. In this Molecule, we’ll use that guarantee, examine associated values and ordering, compare switch statements with expressions, and see why a convenient default can sometimes hide a missing design decision.

A decision for every state

Consider a small synchronization model and a function that turns it into a status line:

enum SyncState {
    case idle
    case syncing(progress: Int)
    case failed(reason: String)
    case finished
}

func status(_ state: SyncState) -> String {
    switch state {
    case .idle:
        return "Waiting"
    case let .syncing(progress):
        return "Syncing: \(progress)%"
    case let .failed(reason):
        return "Failed: \(reason)"
    case .finished:
        return "Complete"
    }
}

print(status(.idle))                     // Waiting
print(status(.syncing(progress: 40)))    // Syncing: 40%
print(status(.failed(reason: "Offline"))) // Failed: Offline
print(status(.finished))                 // Complete

Each call selects one branch. The .syncing(progress: 40) case binds 40 to progress; the failed case binds "Offline" to reason. The other two cases have no associated data. Unlike a sequence of independent if checks, this one decision describes all four states in one place.

There is no default here. That is intentional. If you add case paused to SyncState without updating status, the compiler rejects the non-exhaustive switch. It cannot decide what the screen should say for the new case, so it asks you to decide.

A pattern can ask a second question

Exhaustiveness does not require every branch to be a single enum-case name. A case can bind data and use where to test a condition. The order matters because the first matching case wins:

func priority(_ state: SyncState) -> String {
    switch state {
    case .syncing(let progress) where progress >= 90:
        return "Almost done"
    case .syncing:
        return "Working"
    case .failed:
        return "Needs attention"
    case .idle, .finished:
        return "No action"
    }
}

print(priority(.syncing(progress: 95)))     // Almost done
print(priority(.syncing(progress: 20)))     // Working
print(priority(.failed(reason: "Offline"))) // Needs attention

For progress 95, both .syncing patterns could describe the enum case, but the first also satisfies progress >= 90, so it returns "Almost done". For progress 20, the condition fails and the next .syncing branch returns "Working". The failed value returns "Needs attention"; its reason is deliberately ignored in this function. Finally, .idle and .finished share the same result because both mean no immediate action for this particular decision.

This ordering has a practical consequence: placing the unconditional case .syncing first would make the later progress-specific case unreachable. Put the more specific pattern first. The where condition is a runtime rule about the associated value, not a new enum case.

switch can produce a value

Sometimes each state maps to one value rather than a series of actions. Modern Swift supports a switch expression, so the mapping can sit directly where the value is needed:

let phase: SyncState = .finished

let label: String = switch phase {
case .idle: "Waiting"
case .syncing: "In progress"
case .failed: "Error"
case .finished: "Done"
}

print(label) // Done

The phase value is .finished, so the expression selects "Done" and initializes label. Every branch yields a String, and the switch is exhaustive. Unlike the earlier function, this mapping intentionally ignores progress numbers and failure reasons because it only needs a short label.

A switch expression is useful for a concise, total mapping. It is not a reason to compress complicated work into one expression. If each branch needs several steps, a normal switch statement or a small function may communicate the intent better. Switch expressions were introduced in Swift 5.9; do not assume they compile under older language toolchains.

The hidden cost of default

A default branch can make a switch exhaustive even when the type has many values. That is essential for open-ended inputs such as arbitrary integers or strings. But for a local enum with a known set of cases, it can hide future changes:

func description(_ state: SyncState) -> String {
    switch state {
    case .failed(let reason):
        return "Failure: \(reason)"
    default:
        return "Not failed"
    }
}

print(description(.idle))                      // Not failed
print(description(.failed(reason: "Timeout"))) // Failure: Timeout

This code is correct for its stated question: is the operation a failure? The .idle value falls into default, and the failed value binds "Timeout". But if we later add .paused, it also falls into default without a compiler error. That might be acceptable for a failure badge; it would be a poor choice for a full status screen.

This is the distinction worth keeping: exhaustive syntax does not always mean an exhaustive design review. An explicit case for each known state lets a new state force a new decision. A broad default trades that reminder for convenience.

Optional state: absence is another possibility

An optional enum has two levels: the optional may be nil, or it may contain one of the enum’s cases. A switch can make both levels visible:

let option: SyncState? = nil
switch option {
case nil:
    print("Missing state") // Missing state
case .some(.finished):
    print("Finished state")
case .some:
    print("Other state")
}

let other: SyncState? = .finished
switch other {
case nil:
    print("Missing state")
case .some(.finished):
    print("Finished state") // Finished state
case .some:
    print("Other state")
}

The first optional is nil, so only "Missing state" prints. The second contains .finished, so it matches .some(.finished) and prints "Finished state". The final .some branch covers all other non-nil cases, such as .idle or .failed. No implicit fallthrough occurs: after the first matching branch finishes, the switch ends.

Here the broad .some branch is deliberate. We are distinguishing absence, finished, and everything else. If the UI needs separate messages for syncing and failure, that grouping is too broad and should be expanded.

Know which enums can grow outside your code

The compiler can demand every known case of your own enum. There is a separate concern when an enum comes from a library that supports adding cases without breaking binary compatibility. Swift calls such an enum nonfrozen. A switch over a nonfrozen enum needs a fallback for future cases, even when you have named every case currently known.

For that situation, @unknown default is preferable to a plain default when you want the compiler to warn as the library introduces a newly known case. It handles cases unknown to the version of the library you compiled against while preserving a reminder to review newly available cases. This is not a rule that every ordinary local enum requires @unknown default: its purpose is library evolution.

Also remember that a switch does not fall through automatically. Swift selects the first matching pattern and executes its branch. An explicit fallthrough exists, but it bypasses the next case’s matching condition; it is rarely the right tool for modeling state.

Use the compiler as a design partner

Use if case when a local action needs only one case. Use for case when a loop should select matching elements. Use switch when the code is responsible for deciding what every state means. These tools complement each other rather than compete for the shortest syntax.

For a finite enum you own, leaving out default can turn future model changes into visible compiler errors. That is valuable in UI rendering, state transitions, and domain rules where silently treating a new state like an old one would be misleading. For an intentionally partial question or an open-ended input, a fallback remains useful. The goal is not to ban default; it is to decide whether ignoring distinctions is part of the design.

The best switch is not merely one that compiles today. It is one that makes the next change difficult to overlook.

Sources