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.
| Pattern | Example case | Matches |
|---|---|---|
| Value | case 404: | one exact value |
| List | case 200, 201: | any value in the list |
| Range | case 300..<400: | a value inside the range |
| Tuple | case (0, _): | a pair by position, _ ignores one |
| Binding | case (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
- 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
fallthroughexplicitly, but you rarely should.
- 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.
- Sprinkling
defaulton your own enums. Adefaultswallows any case you did not name. On an enum you own, that throws away the compiler's best feature: without adefault, adding a new case forces you to update every switch. With one, the new case silently falls intodefaultand goes unhandled.
- Forgetting to bind the associated value. Writing
case .move:when the case is actuallycase move(steps: Int)discards the data you need. You must bind it, as incase .move(let steps):, to use the number inside the branch.
- Misreading how
wherefails. When a case's pattern matches but itswhereclause is false, the switch does not jump todefault; 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.
- Confusing half-open and closed ranges.
0..<50includes0but stops before50, while0...50includes50. 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.
- Force-unwrapping an optional instead of matching
nil. When switching over an optional, handle the empty case withcase nil(or bind the value withcase 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.
- Assuming a
Stringcase does partial or case-insensitive matching.case "quit":matches only the whole stringquitexactly. 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.
- Forgetting that
IntandStringswitches need adefault. These types have far too many values to enumerate, so the compiler cannot prove your cases are exhaustive and will require adefault. 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 omitdefault. Let the compiler remind you, at build time, of every switch that must change when you add a case. Reservedefaultfor genuinely open types likeIntandString.
- 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
wherefor refinements, not nestedif. When a case applies only under an extra condition, express it ascase .celsius(let t) where t > 38.0:instead of matching broadly and then branching with anifinside 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?andcase nilto unwrap an optional inside a switch, which keeps both the present and absent paths visible and side by side, rather than force-unwrapping or scatteringif letaround 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
- Grade with ranges. Write a function that takes an
Intscore from0to100and switches over half-open ranges to return"fail"for below50,"pass"for50up to70,"merit"for70up to90, and"distinction"otherwise. Call it with49,50,70, and95, and predict each result before checking, paying attention to which side of each boundary the edge values land on.
- Classify a point without a default. Write a switch over a
(Int, Int)tuple that printsoriginfor(0, 0),on an axiswhen exactly one coordinate is0, andin the open planeotherwise. Arrange the cases so the switch is exhaustive with nodefault, and explain in a comment why the last case makes it complete.
- Guard an enum case with
where. Defineenum Light { case red, yellow, green }and a function that returns how many seconds to wait, but add awhereclause so agreenlight returns0only when a passed-inisClearflag is true, and otherwise returns a caution value. Note in a comment why the guardedgreencase must come before an unguarded one.
- Repair the parser. Take the command parser from the Real World Example and add a
case badArguments(command: String, reason: String)toCommand. Changeparseso thatmovewith a non-integer argument returns.badArgumentsexplaining the problem instead of silently defaulting the step count to0, and handle the new case inrun. Confirm thatmove fastnow reports an error rather than moving zero steps.