skip to content

In Swift, how do you bind an enum case's associated values in a switch, and when do you use if case, guard case or for case instead?

level: middleimportance: must knowfreq 75%

answer

  1. let inside or before the case
  2. where filters after the match
  3. if case uses =, not ==
  4. compound cases bind identical names
  5. for case skips non-matching elements

basics

~20 s

Bind payload values with let or var inside the case pattern, as in case .failure(let status, _), optionally filtered by where. Use if case or guard case to test one case without a switch, and for case to loop over matches.

solid answer

~50 s

`case .ok(let status, let body)` and `case let .ok(status, body)` are equivalent; the second puts one `let` in front when every value is bound as a constant. `var` binds a mutable local copy, and `_` or a literal such as `.ok(200, _)` matches without binding. A `where` clause runs after the pattern matches and can use the bound names. Outside a switch, `if case .redirect(let location) = response` tests one case with `=` rather than `==`, which needs an `Equatable` conformance, and `guard case` does the same with an early exit. `for case let .failure(status, message) in responses where status < 500` runs its body only for matching elements. In a compound case every pattern must bind the same names with the same types, and a `where` written after the last pattern applies only to that pattern.

code

swift · 35 lines
swift
enum Response {
    case ok(status: Int, body: String)
    case redirect(location: String)
    case failure(status: Int, message: String)
}

func handle(_ response: Response) -> String {
    switch response {
    case .ok(let status, let body) where body.isEmpty:
        return "\(status): empty body"
    case let .ok(status, body):
        return "\(status): \(body.count) bytes"
    case .redirect(let location):
        return "go to \(location)"
    case .failure(let status, _) where status >= 500:
        return "retry later (\(status))"
    case .failure(_, var message):
        message += "!"
        return message
    }
}

func failureStatus(_ response: Response) -> Int? {
    guard case .failure(let status, _) = response else { return nil }
    return status
}

let responses: [Response] = [.ok(status: 200, body: ""), .redirect(location: "/login"),
                             .failure(status: 503, message: "down"), .failure(status: 404, message: "not found")]
for response in responses { print(handle(response)) }
if case .redirect(let location) = responses[1] { print("redirect to", location) }
print(failureStatus(responses[2]) ?? -1)
for case let .failure(status, message) in responses where status < 500 {
    print("client failure", status, message)
}

go deeper

for a junior

Recall both binding spellings, that where filters after a match, and that if case puts the pattern before a single equals sign.

for a middle

Explain why payload enums are matched with patterns rather than ==, how guard case keeps a bound value in scope, and why compound cases must bind identical names and types.

for a senior

Catch the where-on-the-last-pattern trap in review and prefer guard case for early exits, so handlers stay flat and every bound value has an obvious scope.

for a principal

Ask for bare case patterns such as case .ok wherever the payload is unused, so that adding a payload field later forces edits only where code really destructures it.

## The payload is reached only through a pattern An enum case with **associated values** — `case failure(status: Int, message: String)` — carries data, but Swift gives you no property to read it from. The only way in is a **pattern** that names the case and says what to do with each associated value. That pattern can sit in a `switch` case label, or in the condition of `if`, `guard`, `while` and `for`-`in`, where it is introduced with the `case` keyword. The examples here use an HTTP response handler: `enum Response { case ok(status: Int, body: String); case redirect(location: String); case failure(status: Int, message: String) }`. ## Binding forms | Pattern | What it does | |---|---| | `case .ok(let status, let body)` | Binds both values as constants | | `case let .ok(status, body)` | Same thing, one `let` distributed over every name | | `case .failure(_, var message)` | Binds a mutable local copy; changing it does not touch the enum value | | `case .ok(200, _)` | Matches only status 200; binds nothing | | `case .ok` | Matches any `.ok`, ignoring the whole payload | The book allows the single leading `let` or `var` when every value is extracted the same way; mixing constants and variables needs the per-value form. ## `where` clauses A **`where` clause** adds a Boolean condition that runs only after the pattern has matched, and it can use the names the pattern bound. - `case .ok(let status, let body) where body.isEmpty:` handles empty bodies before a general `.ok` case. - If the condition is false, matching moves on to the next case; the body does not start. - A case guarded by `where` does not count toward exhaustiveness, so a later unguarded case for the same enum case is still needed. - In a compound case, `where` belongs to the **pattern it follows**. `case .ok(let status, _), .failure(let status, _) where status >= 500:` filters only `.failure`; every `.ok` matches. Swift 6.4 warns: `'where' only applies to the second pattern match in this 'case'`, with notes suggesting you duplicate the `where` or add a line break if that is intended. ## One case outside a switch A full `switch` is heavy when only one case matters. Three statements take a case pattern directly: 1. **`if case`** — `if case .redirect(let location) = response { … }`. The pattern goes on the left of a single `=`. It needs no `Equatable` conformance; `response == .redirect(location: "/login")` fails with `binary operator '==' cannot be applied to two 'Response' operands` unless `Response` declares `Equatable`. A literal sub-pattern still compares: `if case .redirect("/login") = response` compiles. Forgetting `case` (`if let .redirect(location) = response`) is rejected with `pattern matching in a condition requires the 'case' keyword`. 2. **`guard case`** — `guard case .failure(let status, _) = response else { return nil }` exits early on every other case and leaves `status` in scope for the rest of the function, which keeps handlers flat. 3. **`for case`** — `for case let .failure(status, message) in responses where status < 500 { … }` runs the body only for elements that match; non-matching elements are skipped and the loop carries on. The optional pattern works the same way: `for case let code? in codes` visits only the non-nil values. Conditions combine with commas: `if case .ok(let s, _) = r, s >= 200 { … }`. ## Compound cases and their rule Several patterns in one case share one body, so the body must be able to use every name whichever pattern matched. Swift therefore requires each pattern to bind **the same names with the same types**. `case .ok(let status, _), .redirect:` fails with `'status' must be bound in every pattern`; `case .ok(let status, _), .failure(let status, _):` compiles because both bind an `Int` called `status`. ## Mistakes reviewers catch 1. Writing `==` against a payload case and then adding an `Equatable` conformance just to make one `if` compile, when `if case` needed none. 2. A `where` after a compound case that silently applies to its last pattern only. 3. Binding values the body never uses; `_` or a bare `case .ok` says the payload does not matter, and a bare case pattern keeps compiling if a field is later added to the payload. 4. Nesting the whole function inside `if case` where `guard case` would keep the happy path at the left margin. 5. Expecting `var` in a pattern to mutate the enum value in place; it binds a copy.

  • Why does if response == .redirect(location: "/login") fail to compile for a plain Swift enum with associated values?
    `==` needs an `Equatable` conformance, and an enum with associated values only has one if it declares it. Swift reports `binary operator '==' cannot be applied to two 'Response' operands`. A case pattern needs no conformance: `if case .redirect("/login") = response` compares the payload inside the pattern itself.
  • What does case .ok(let status, _), .failure(let status, _) where status >= 500: actually test in a Swift switch?
    The `where` belongs to the last pattern only, so every `.ok` matches whatever its status and only `.failure` is filtered. Swift 6.4 warns `'where' only applies to the second pattern match in this 'case'`. Repeat the `where` after each pattern, or split the compound case in two.
  • When is guard case a better choice than if case in Swift?
    When the rest of the function needs the bound value. `guard case .failure(let status, _) = response else { return nil }` leaves on every other case and keeps `status` in scope afterwards, so the main logic stays at the outer level instead of nesting inside an `if case` body.

  • An enum's associated values can be read as properties without any pattern.
  • if case compares with ==, so the enum must conform to Equatable.
  • case let .ok(status, body) binds differently from case .ok(let status, let body).
  • A where clause after a compound case applies to every pattern in it.
  • for case stops the loop at the first element that does not match.
  • Each pattern of a compound case may bind different names.