In Swift, how does a switch match tuple and range patterns, such as a deep link's (host, path) pair or an HTTP status code?
answer
- element by element, left to right
- underscore ignores one slot
- ranges match through ~=
- first match in source order
- Int switches still need default
basics
~20 sA Swift switch matches a tuple element by element, with _ ignoring a position, and a range by containment. The first matching case in source order wins; a switch over Int or String still needs a default case.
solid answer
~40 sA tuple pattern such as `("app.example.com", "/")` matches when every element matches its own sub-pattern, and `_` accepts anything in its slot, so `(_, "/help")` matches any host. A range such as `200..<300` or `500...` is an expression pattern: Swift evaluates `pattern ~= value`, and the standard library's `~=` for ranges calls `contains(_:)`. Several patterns separated by commas share one body, and `let` can bind an element for a `where` clause. Cases behave as if tried in source order and only the first match runs, so overlapping ranges compile and the earlier one wins. The switch must also be exhaustive: the compiler can prove coverage for enums, `Bool` and tuples of them, but it does not reason about ranges, so a switch over `Int` needs `default` even when the ranges cover every value.
code
swift · 33 lines// A deep-link router matching (host, path) tuples
func route(host: String, path: String) -> String {
switch (host, path) {
case ("app.example.com", "/"):
return "home"
case ("app.example.com", let p) where p.hasPrefix("/orders/"):
return "order \(p.dropFirst(8))"
case (_, "/help"), (_, "/support"):
return "help"
default:
return "unknown link"
}
}
// An HTTP response handler matching status-code ranges
func describe(status: Int) -> String {
switch status {
case 200..<300:
return "success"
case 301, 302, 307, 308:
return "redirect"
case 400..<500:
return "client error"
case 500...:
return "server error"
default:
return "unexpected"
}
}
print(route(host: "app.example.com", path: "/orders/42"))
print(route(host: "docs.example.com", path: "/support"))
print(describe(status: 204), describe(status: 302), describe(status: 503), describe(status: 99))go deeper
Recall the shapes: a tuple compares position by position, underscore skips a slot, commas list alternatives, ranges test containment, and the first matching case wins.
Explain that a range case is an expression pattern resolved through the standard library's ~= operator, and that this is why an Int switch needs default even when its ranges look complete.
Show that you order cases narrow before broad, because Swift accepts overlapping ranges silently, and keep a default that logs or rejects unexpected status codes instead of guessing.
Treat routing tables written as tuple switches as review hotspots: reordering one case silently changes behaviour, so ask for a test per route and cases ordered by specificity.
## Two everyday shapes Two pieces of app code lean on Swift's `switch` patterns more than almost anything else: a **deep-link router** that decides what to show for a `(host, path)` pair, and an **HTTP response handler** that buckets a status code. Both are written as one `switch` whose cases are **patterns** rather than plain values, and both rely on the same three rules: how a pattern matches, which case wins when several match, and when the compiler accepts the `switch` as complete. ## Tuple patterns A **tuple pattern** is a parenthesised list of sub-patterns, one per element of the tuple being switched on. It matches only when **every** element matches its own sub-pattern. - A literal such as `"app.example.com"` compares that element with `==`. - The **wildcard** `_` matches any value in its slot and binds nothing, so `(_, "/help")` matches every host. - A **value-binding** sub-pattern such as `let p` matches anything and gives the element a name for the case body and for a `where` clause: `case ("app.example.com", let p) where p.hasPrefix("/orders/")`. - Several patterns separated by commas form a **compound case**: `case (_, "/help"), (_, "/support"):` runs one body when either matches. Swift has no pattern that destructures an array, so a router either switches on a `String` path or splits the path first and switches on the pieces it cares about. ## Range patterns are expression patterns A range in a case label is an **expression pattern**. Swift does not compare it with `==`; it evaluates `pattern ~= value` using the **pattern-matching operator**. The standard library declares `~=` on `RangeExpression` as `pattern.contains(value)`, and for `Range` that is a bounds check (`lowerBound <= element && element < upperBound`). So: - `case 200..<300:` matches 200 through 299; - `case 500...:` uses a one-sided range and matches 500 and everything above; - `case 301, 302, 307, 308:` mixes single values into a compound case; each value goes through the generic `~=` for `Equatable` types, which is `==`. Ranges compose with tuples: `case (200..<300, _):` matches a `(status, body)` pair whose status is a success. ## Order: the first match wins The book states that matching behaves **as if** cases are tried in source order, and only the first matching case's body runs. Two consequences matter in review: 1. **Overlap is legal.** `case 200..<300:` followed by `case 204:` compiles, and 204 always lands in the range case. When tested on Swift 6.4, that ordering produced no warning at all. 2. **Specific before general.** Put the narrow case first: `case 204:` above `case 200..<300:`, or the `/orders/` route above a catch-all for the same host. The compiler does warn about some provably redundant cases — a literal that an earlier pattern already lists draws `literal value is already handled by previous pattern; consider removing it` — but it never ranks cases by specificity. ## Exhaustiveness Every Swift `switch` must be **exhaustive**: every possible value of the control expression's type must match some case. What the compiler can prove depends on the type. | Control type | Can the compiler prove coverage? | What you write | |---|---|---| | An enum you compiled | Yes, case by case | Every case, or `default` | | `Bool`, or a tuple of `Bool`s and enums | Yes, element by element | Every combination, using `_` | | `Int`, `String`, `Double` | No | `default` | | Anything matched by ranges or other expression patterns | No | `default` | The last row surprises people: cases `Int.min..<200`, `200..<300` and `300...Int.max` together cover every `Int`, yet the compiler reports `switch must be exhaustive` with the note `add a default clause`. The checker does not look inside `~=`, so no set of ranges is ever proven complete. ## Mistakes reviewers catch 1. Reading `_` as an empty string or zero instead of a wildcard. 2. Expecting a prefix or substring test from a string literal; literals compare with `==`, and a prefix needs `let` plus `where`. 3. Placing a broad range above a narrow value and wondering why the narrow body never runs. 4. Deleting `default` from an `Int` switch because the ranges "obviously" cover everything. A useful habit for status codes is a `default` that logs or rejects the unexpected value rather than guessing, because servers do return codes nobody planned for.
- Why does a Swift switch over a (Bool, Bool) tuple compile without default when an Int switch whose ranges cover everything does not?The exhaustiveness checker reasons about types it can enumerate: enum cases, `Bool`'s two values, and tuples built from them, so `(true, true)`, `(true, false)` and `(false, _)` are provably complete. A range is an expression pattern, a call to `~=` the checker does not evaluate, so it cannot prove any set of ranges covers `Int` and asks for a default clause.
- Is case 204 reachable if it comes after case 200..<300 in the same Swift switch?No. Cases behave as if tried in source order and only the first match runs, so 204 always lands in the range case. Swift 6.4 compiled that ordering without a warning when tested; it warns only about some provably redundant cases, such as a literal an earlier pattern already lists. Put the narrow case first.
- How do you bind part of a tuple while matching the rest literally?Use a value-binding sub-pattern in that slot: `case ("app.example.com", let path) where path.hasPrefix("/orders/"):` requires the host to equal the literal and binds the path as a constant for the `where` clause and the body. `var path` binds a mutable local copy instead.
- A switch over Int is exhaustive once its ranges cover every value.
- Overlapping cases are a compile error in Swift.
- When two cases match, Swift runs the most specific one.
- A range case compares with ==, so 404 cannot match 400..<500.
- An underscore in a tuple pattern matches only an empty string or zero.