Switch and Pattern Matching

Switch and Pattern Matching in Swift: Picture an old mechanical coin-sorting machine. Coins roll one at a time down an inclined rail, and beneath the rail sits…

The Analogy: The Coin-Sorting Machine

Picture an old mechanical coin-sorting machine. Coins roll one at a time down an inclined rail, and beneath the rail sits a row of holes, each cut to exactly one coin's diameter. As a coin travels, it tries each hole in turn, and it drops through the very first hole it fits. The instant it drops, it is done: it never reaches any of the holes further down the rail. The order of the holes is not decoration, it is the logic, because the machine always tries them from top to bottom and stops at the first success.

The holes are not all single-size. Some are wide slots that accept any coin whose diameter falls within a band, which is how the machine handles a whole range at once instead of one exact size. A few stations read two dimensions together, diameter and thickness, using a paired gauge that only releases a coin when both readings match the shape it expects. And a coin often has a number stamped into its face; a reading head at a station can lift that stamped number off and write it onto the tally sheet as the coin passes, so the station both matches the coin and captures the value printed on it.

Some stations add a second, finer test. A coin might physically fit the hole, but a secondary gauge beside it checks the stamped number against an extra condition and only lets the coin drop if that condition also holds; if it fails the extra check, the coin simply carries on to the next hole down. At the very bottom sits an oversized catch-all bin that swallows anything which matched no earlier hole, and the machine's safety interlock will not let the line start at all unless either that catch-all bin is in place or the holes provably cover every coin the mint is known to produce.

The failures are instructive. A technician short on floor space unbolts the catch-all bin to save room; the first unfamiliar coin then matches no hole, rolls off the end of the rail, and jams the return chute, freezing the whole line, which is exactly why a switch with neither a catch-all nor provably complete cases refuses to compile. The subtler disaster is installing a wide range-slot above a narrow exact-size hole meant for one special coin: every special coin now drops through the wide slot first and is quietly misfiled, and because nothing jams, nobody notices for weeks. An over-broad case placed before a specific one silently shadows it, and the machine keeps running while sending the wrong coins to the wrong bin.


Syntax or Core Structure

A switch in Swift takes one value and compares it against a list of case patterns, top to bottom, running the body of the first case that matches and then stopping. Unlike C, there is no implicit fall-through, so each case is self-contained and needs no break. The switch must be exhaustive: either the cases provably cover every possible value, or a default case catches the rest.

let statusCode = 404

switch statusCode {
case 200, 201:            // a list pattern: any of these values
    print("success")
case 300..<400:           // a half-open range: 300 up to, not including, 400
    print("redirect")
case 404:                 // a single exact value
    print("not found")
case 500...599:           // a closed range: 500 through 599 inclusive
    print("server error")
default:                  // required: Int has too many values to cover
    print("other: \(statusCode)")
}

// A tuple pattern matches several values at once, and let binds a piece.
let point = (0, 4)
switch point {
case (0, 0):
    print("origin")
case (let x, 0):
    print("on the x-axis at \(x)")
case (0, let y):
    print("on the y-axis at \(y)")
case (let x, let y):
    print("at \(x), \(y)")
}

The pieces to hold onto are: cases are tried in order and the first match wins; a case can be an exact value, a comma-separated list, or a range; a tuple pattern matches a compound value position by position; let inside a pattern lifts the matched value out for use in the body; and _ matches anything while discarding it. Everything later in this lesson is a combination of these.


Technical Depth: Matching, Binding, and Exhaustiveness

A Swift switch is far more than a tidy if/else chain. It matches by pattern, binds values out of what it matched, and is checked by the compiler for completeness. This section works through each of those in the order the coin machine met them: first-match ordering, then ranges and tuples, then enums with conditions, then optionals.

First match wins, and there is no fall-through

The machine drops a coin through the first hole it fits and stops. A Swift switch does the same: it runs exactly one case, the first whose pattern matches, and then leaves. This is why a broad case placed above a narrow one hides the narrow one entirely.

let score = 72
switch score {
case 0..<50:
    print("fail")
case 50..<70:
    print("pass")
case 70..<90:
    print("merit")
default:
    print("distinction")
}

let n = 5
switch n {
case let x where x < 10:
    print("small")
case 5:
    print("exactly five")
default:
    print("other")
}

Output:

merit
small

The first switch prints merit: 72 is not below 50, not in 50..<70, but does fall in 70..<90, so that case runs and the default is never consulted. The second switch prints small, not exactly five. Even though n is 5, the earlier case let x where x < 10 matches first and wins, so the specific case 5 below it is dead code. That is the shadowing failure of the coin machine reproduced exactly, and it is why case order is part of the logic.

Ranges, tuples, and value binding

Each hole on the rail is a kind of pattern. Some match one exact size, some a band of sizes, and some read two dimensions at once. The table below names the pattern kinds you will use most, and the code shows a tuple switch that stays exhaustive without any default.

PatternExample caseMatches
Valuecase 404:one exact value
Listcase 200, 201:any value in the list
Rangecase 300..<400:a value inside the range
Tuplecase (0, _):a pair by position, _ ignores one
Bindingcase (let x, 0):binds part of the value to a name
let point = (0, 4)
switch point {
case (0, 0):
    print("origin")
case (let x, 0):
    print("on the x-axis at \(x)")
case (0, let y):
    print("on the y-axis at \(y)")
case (let x, let y):
    print("at \(x), \(y)")
}

Output:

on the y-axis at 4

Walking the cases for (0, 4): it is not (0, 0); it is not (let x, 0) because the second element is 4, not 0; it does match (0, let y), binding y to 4, so the body prints on the y-axis at 4. The final (let x, let y) never runs. That last case is important for another reason: because it matches every possible pair of integers, the compiler can see the switch is exhaustive and does not require a default. Binding a whole value with let is how you turn "some pair" into a proven-complete set of cases.

Enums, associated values, and where clauses

Switching over an enum is where pattern matching pays off most. A case can pull the associated value out of an enum with let, and a where clause adds the secondary gauge: the coin fits the hole physically, but only drops if the stamped number also passes an extra test.

enum Reading {
    case celsius(Double)
    case fahrenheit(Double)
}

func describe(_ r: Reading) -> String {
    switch r {
    case .celsius(let t) where t > 38.0:
        return "fever: \(t) C"
    case .celsius(let t):
        return "body temp: \(t) C"
    case .fahrenheit(let f):
        return "in F: \(f)"
    }
}

print(describe(.celsius(37.0)))
print(describe(.celsius(39.5)))
print(describe(.fahrenheit(98.6)))

Output:

body temp: 37.0 C
fever: 39.5 C
in F: 98.6

For .celsius(37.0), the first case fits the shape but its where t > 38.0 fails, so the coin rolls on to the next .celsius(let t) case and prints body temp: 37.0 C. For .celsius(39.5), the where passes and the first case wins with fever: 39.5 C. For .fahrenheit(98.6), only the last case matches. Note there is no default: the two enum cases are both handled, so the switch is exhaustive on its own. The key subtlety is that a failed where does not jump to default; it simply moves to the next case in order, which is why the plain .celsius(let t) must come after the guarded one.

Optional patterns and the closed-set guarantee

An Optional is itself an enum with two cases, .some(value) and .none, so you can switch over it. Swift gives the .some case a shorthand: case let value? binds the wrapped value, and case nil matches the empty one. Handling both makes the switch exhaustive.

let maybe: [Int?] = [3, nil, 7]
for item in maybe {
    switch item {
    case let value?:
        print("got \(value)")
    case nil:
        print("missing")
    }
}

Output:

got 3
missing
got 7

The array holds three optionals. For 3, the pattern case let value? matches .some(3) and binds value to 3, printing got 3. For nil, case nil matches and prints missing. For 7, the first case matches again. Because Optional has exactly two cases and both are handled, no default is needed, and the compiler guarantees at build time that no value can slip through unhandled. This closed-set guarantee is the software version of the safety interlock: the line will not start unless every coin has somewhere to go.


Real World Example: A Tiny Command Parser

A line-based command parser is a natural fit for pattern matching. Each input line becomes one of a small, fixed set of commands, which is exactly what an enum with associated values models, and dispatching on that enum is exactly what a switch does. Here the parser turns raw text into a Command, and the runner switches over the command to carry it out against a moving cursor position.

enum Command {
    case move(steps: Int)
    case write(text: String)
    case quit
    case unknown(String)
}

func parse(_ line: String) -> Command {
    let parts = line.split(separator: " ", maxSplits: 1).map(String.init)
    let verb = parts.first ?? ""
    switch verb {
    case "move":
        let steps = Int(parts.count > 1 ? parts[1] : "") ?? 0
        return .move(steps: steps)
    case "write":
        return .write(text: parts.count > 1 ? parts[1] : "")
    case "quit":
        return .quit
    default:
        return .unknown(line)
    }
}

func run(_ commands: [Command]) {
    var position = 0
    for command in commands {
        switch command {
        case .move(let steps):
            position += steps
            print("moved to \(position)")
        case .write(let text):
            print("wrote: \(text)")
        case .quit:
            print("stopping at \(position)")
        case .unknown(let raw):
            print("ignored: \(raw)")
        }
    }
}

let script = ["move 3", "write hello", "move 2", "spin 4", "quit"]
run(script.map(parse))

Output:

moved to 3
wrote: hello
moved to 5
ignored: spin 4
stopping at 5

The two enums and two switches divide the work cleanly. parse switches on the verb string to decide which Command a line becomes, and run switches on the Command to decide what to do, binding the associated values (steps, text, raw) as it goes. Because a Command is always exactly one of four cases, there is no room for an input to be half-parsed or a step to be in an undefined state.

Following the script: move 3 advances the cursor from 0 to 3 and prints moved to 3; write hello prints wrote: hello without moving; move 2 advances to 5 and prints moved to 5; spin 4 is not a known verb, so parse returns .unknown("spin 4") and run prints ignored: spin 4; finally quit prints stopping at 5, reporting the position the cursor reached.

The switch inside run has no default, and that is deliberate. Because it handles all four Command cases explicitly, the compiler treats it as exhaustive. If someone later adds a case pause to Command, this switch will stop compiling until they handle it, which turns "we forgot to deal with the new command" from a silent runtime gap into a build error the machine points straight at.

The genuine flaw is in parse, where .unknown is asked to mean two different things and one real error escapes it entirely. An unrecognised verb like spin and a genuinely empty line both collapse into .unknown, which already blurs "I do not know this command" together. Worse, a recognised command with a bad argument does not even reach .unknown: move fast matches case "move", Int("fast") returns nil, and ?? 0 silently rewrites it as move 0, so the parser reports success while quietly discarding the user's mistake. The type cannot distinguish an unknown command from a known one given garbage, so callers cannot tell a typo from a real problem. The fix is a dedicated case badArguments(command: String, reason: String) plus validating the integer instead of defaulting it, so a bad step count becomes a reported error rather than a silent zero.


Common Mistakes

  1. Expecting C-style fall-through. In Swift a matched case runs and the switch ends; execution does not spill into the next case. Programmers coming from C add empty cases expecting them to fall through and are surprised. If you genuinely want the next case's body too, you must write fallthrough explicitly, but you rarely should.
  1. Ordering a broad case above a specific one. Because the first match wins, a wide range or a where-free binding placed above a narrow case silently shadows it. The narrow case becomes dead code that never runs, and the compiler may not warn you. Put the most specific cases first.
  1. Sprinkling default on your own enums. A default swallows any case you did not name. On an enum you own, that throws away the compiler's best feature: without a default, adding a new case forces you to update every switch. With one, the new case silently falls into default and goes unhandled.
  1. Forgetting to bind the associated value. Writing case .move: when the case is actually case move(steps: Int) discards the data you need. You must bind it, as in case .move(let steps):, to use the number inside the branch.
  1. Misreading how where fails. When a case's pattern matches but its where clause is false, the switch does not jump to default; it moves on to the next case in order. This is why a guarded case must sit above the unguarded version of the same pattern, or the unguarded one will catch everything first.
  1. Confusing half-open and closed ranges. 0..<50 includes 0 but stops before 50, while 0...50 includes 50. Off-by-one bugs at the boundary come from reaching for the wrong one; a value that lands exactly on the edge falls into a different case than you expected.
  1. Force-unwrapping an optional instead of matching nil. When switching over an optional, handle the empty case with case nil (or bind the value with case let x?) rather than force-unwrapping with ! inside a case. A force-unwrap turns a missing value into a crash instead of a handled branch.
  1. Assuming a String case does partial or case-insensitive matching. case "quit": matches only the whole string quit exactly. A trailing space, a capital letter, or extra text will not match. Normalise the input first if you need loose matching, rather than expecting the switch to do it.
  1. Forgetting that Int and String switches need a default. These types have far too many values to enumerate, so the compiler cannot prove your cases are exhaustive and will require a default. Only closed types like enums, Bool, or fully covered tuples can be exhaustive without one.

Best Practices

  • Order cases from specific to general. Since the first match wins, put narrow, exact cases at the top and broad ranges or catch-bindings at the bottom. This mirrors the coin machine's narrow-holes-first layout and keeps specific cases from being shadowed.
  • Prefer exhaustive enum switches over default. For enums you control, handle every case explicitly and omit default. Let the compiler remind you, at build time, of every switch that must change when you add a case. Reserve default for genuinely open types like Int and String.
  • Bind associated values right in the pattern. Use case .move(let steps): to lift the data out at the point of the match rather than re-fetching it in the body. It keeps the value's origin obvious and the case body focused on what to do with it.
  • Use where for refinements, not nested if. When a case applies only under an extra condition, express it as case .celsius(let t) where t > 38.0: instead of matching broadly and then branching with an if inside the body. The intent stays in the pattern where a reader looks first.
  • Reach for tuple patterns to match several values at once. When a decision depends on two or three values together, switch over a tuple of them rather than nesting switches. switch (isLoggedIn, role) reads as a single decision table instead of a staircase of conditions.
  • Model closed sets as enums so switches can be exhaustive. If a value is always one of a fixed set of states, define an enum for it. That is what lets the compiler check completeness, and it turns "did I handle every state" from a worry into a guarantee.
  • Handle optionals with the optional pattern. Prefer case let value? and case nil to unwrap an optional inside a switch, which keeps both the present and absent paths visible and side by side, rather than force-unwrapping or scattering if let around the switch.
  • Keep case bodies short. If a case needs more than a few lines, call a well-named function from it. A switch is easiest to read when each case is a one-line statement of intent, and long bodies hide the shape of the decision the switch is making.

Practice Exercises

  1. Grade with ranges. Write a function that takes an Int score from 0 to 100 and switches over half-open ranges to return "fail" for below 50, "pass" for 50 up to 70, "merit" for 70 up to 90, and "distinction" otherwise. Call it with 49, 50, 70, and 95, and predict each result before checking, paying attention to which side of each boundary the edge values land on.
  1. Classify a point without a default. Write a switch over a (Int, Int) tuple that prints origin for (0, 0), on an axis when exactly one coordinate is 0, and in the open plane otherwise. Arrange the cases so the switch is exhaustive with no default, and explain in a comment why the last case makes it complete.
  1. Guard an enum case with where. Define enum Light { case red, yellow, green } and a function that returns how many seconds to wait, but add a where clause so a green light returns 0 only when a passed-in isClear flag is true, and otherwise returns a caution value. Note in a comment why the guarded green case must come before an unguarded one.
  1. Repair the parser. Take the command parser from the Real World Example and add a case badArguments(command: String, reason: String) to Command. Change parse so that move with a non-integer argument returns .badArguments explaining the problem instead of silently defaulting the step count to 0, and handle the new case in run. Confirm that move fast now reports an error rather than moving zero steps.