How does a Swift switch use the ~= operator for expression patterns, and what changes when you overload ~= for your own matcher type?
answer
- pattern ~= value behind cases
- Equatable uses ==, ranges contains
- static func ~= on matcher
- implicit member syntax in case
- never counts toward exhaustiveness
basics
~20 sSwift evaluates an expression pattern as pattern ~= value: the standard library's ~= uses == for Equatable values and contains for ranges. Overloading ~= for a matcher type lets custom values sit in case labels, but such a switch always needs default.
solid answer
~40 sA case pattern that is not a wildcard, binding, tuple, enum-case, optional or type-casting pattern is an **expression pattern**, and Swift matches it by evaluating `pattern ~= value`. The standard library declares a generic `~=` for `Equatable` values that returns `a == b`, and `RangeExpression` declares `~=` as `pattern.contains(value)`, which is why `case 200..<300:` works. Declaring your own overload, for example `static func ~= (pattern: StatusClass, value: Int) -> Bool` on a `StatusClass` struct with static constants, lets you write `case .success:` in a switch over an `Int` status code, or `if case .success = status`. The exhaustiveness checker does not evaluate `~=`, so expression patterns never make a switch exhaustive and `default` stays mandatory. Keep the overload on the matcher type: a broad global overload makes surprising case labels compile across the module.
code
swift · 21 linesstruct StatusClass {
let codes: Range<Int>
static let success = StatusClass(codes: 200..<300)
static let clientError = StatusClass(codes: 400..<500)
static let serverError = StatusClass(codes: 500..<600)
static func ~= (pattern: StatusClass, value: Int) -> Bool {
pattern.codes.contains(value)
}
}
func handle(status: Int) -> String {
switch status {
case .success: return "ok"
case .clientError where status == 401: return "sign in again"
case StatusClass.clientError: return "fix the request"
case .serverError: return "retry"
default: return "unexpected \(status)"
}
}
for s in [204, 401, 404, 503, 302] { print(handle(status: s)) }go deeper
Recall that literals and ranges in case labels are matched by the ~= operator, and that ranges use contains.
Explain the expression pattern rule, the standard library's Equatable and RangeExpression overloads, and the difference between case expected and case let expected.
Write a matcher as a struct with static constants and a static ~=, keep default in every such switch, and catch global overloads that widen what case labels accept.
Decide whether a custom matcher earns its keep: it names a domain concept across many switches, but each overload is hidden machinery that readers and the type checker both have to resolve.
## Which patterns go through `~=` Swift has several kinds of pattern, and only one of them calls an operator. | Pattern kind | Example | How it matches | |---|---|---| | Wildcard | `_` | Always | | Value binding | `let code` | Always, and binds a name | | Tuple | `(_, "/help")` | Element by element | | Enumeration case | `.failure(let status, _)` | By case, then payload sub-patterns | | Type casting | `let x as Int`, `is Int` | By runtime type | | **Expression** | `404`, `200..<300`, `expected` | By evaluating `pattern ~= value` | So every literal, range or constant in a case label is an expression pattern, and the **pattern-matching operator** `~=` decides whether it matches. Its left operand is the pattern, its right operand the value being switched on. ## The standard library's overloads - `Policy.swift` declares `func ~= <T: Equatable>(a: T, b: T) -> Bool` returning `a == b`; that is what makes `case 404:` and `case expected:` work. Its doc comment says to use `==` for ordinary equality tests and that `~=` is primarily intended for case statement matching. - An extension on `RangeExpression` declares `static func ~= (pattern: Self, value: Bound) -> Bool` returning `pattern.contains(value)`; for `Range`, `contains(_:)` is a bounds check. - `StringComparable.swift` declares `~=` overloads so that a `String` pattern can match a `Substring` value, and a `Substring` pattern a `String`. You can call the operator directly too: `200..<300 ~= status` is an ordinary `Bool` expression. ## Writing a matcher The usual reason to overload `~=` is to give a domain concept a name in case labels — HTTP status classes in a response handler, say. 1. Declare a matcher type: `struct StatusClass { let codes: Range<Int> }`. 2. Give it named instances as static constants: `static let success = StatusClass(codes: 200..<300)`. 3. Declare the operator on the type: `static func ~= (pattern: StatusClass, value: Int) -> Bool { pattern.codes.contains(value) }`. 4. Use it: `case .success:` in a switch over an `Int`. Swift infers the pattern's type from the `~=` overload, so implicit member syntax works, as does the qualified `StatusClass.success`, a `where` clause, and `if case .success = status`. A **struct with static constants** is the safer shape for the matcher. Inside a case label, a name that resolves to an enum case is read as an enumeration case pattern; when this was tested with Swift 6.4 and an enum matcher, `case StatusClass.success:` over an `Int` failed with `pattern of type 'StatusClass' cannot match 'Int'` even with a `~=` overload declared. Static constants are plain expressions, so they always reach `~=`. ## What the compiler can and cannot check - **Exhaustiveness.** The checker does not look inside `~=`. A switch whose cases are expression patterns is never proven complete, however much the matchers accept: it reports `switch must be exhaustive` with the note `add a default clause`. - **Order.** As with any case, matching behaves as if in source order; overlapping matchers compile and the first wins. - **Scope.** Overload resolution considers every visible `~=`. A global function such as the book's example `func ~= (pattern: String, value: Int) -> Bool` suddenly makes `case "0":` compile in any `switch` over an `Int` in the module. Declaring the operator as a `static func` on the matcher type keeps it tied to that type. ## A related trap: comparing versus binding `case expected:` is an expression pattern: it compares the value with the existing constant `expected` through `~=`. `case let expected:` is a **binding** pattern: it matches everything and declares a new constant that shadows the outer one. Put the binding version first and every later case is dead; Swift 6.4 warns `case will never be executed` on the cases after it. ## When to reach for it - Named classes of values that recur across several switches — status classes, character classes, version ranges. - Matching a value against a predicate-like object that is not itself `Equatable` with the value. - Not for one-off checks: a `where` clause or a plain range is clearer, and every custom overload is one more thing a reader must find.
- In a Swift switch, what is the difference between case expected: and case let expected: ?`case expected:` is an expression pattern that compares the value with an existing constant through `~=`, which is `==` for an `Equatable` type. `case let expected:` is a binding pattern that matches every value and declares a new constant shadowing the outer one, so later cases are unreachable and Swift 6.4 warns `case will never be executed`.
- Why make a Swift ~= matcher a struct with static constants rather than an enum whose cases you match?A name that resolves to an enum case is read as an enumeration case pattern. When tested with Swift 6.4, `case StatusClass.success:` over an `Int` with an enum matcher failed with `pattern of type 'StatusClass' cannot match 'Int'`, despite a `~=` overload. Static constants on a struct are plain expressions and always go through `~=`.
- Can a custom ~= overload make a Swift switch over Int exhaustive if its matchers cover every value?No. Exhaustiveness checking does not evaluate `~=`, so even matchers that together accept every `Int` leave the switch reported as `switch must be exhaustive`, with a note to add a default clause. Keep `default` and make it log or reject the unexpected value.
- Case labels compare with ==, so ~= only matters for ranges.
- A ~= overload that covers every value makes the switch exhaustive.
- case let expected compares the value with an existing constant named expected.
- A global ~= overload only affects the switch it was written for.
- Range patterns iterate over every element to find a match.