skip to content

In a Swift switch over a value of type Any, what do the case is T and case let x as T patterns do, and why does case order matter?

level: middleimportance: should knowfreq 40%

answer

  1. runtime type, subclasses included
  2. is checks, as binds
  3. as wraps another pattern
  4. superclass first hides subclass
  5. Any always needs default

basics

~20 s

case is T matches when the value's runtime type is T or a subclass; case let x as T matches the same values and binds x as T. The first match wins, so a superclass case placed first hides its subclasses.

solid answer

~40 s

Type-casting patterns test the dynamic type of the value being switched on. `case is APIError` matches an `APIError` or any subclass and binds nothing; `case let limited as RateLimited` matches the same way and binds the value already cast to `RateLimited`. The `as` pattern wraps another pattern, so `case let (status, body) as (Int, String)` casts and destructures a tuple, and a `where` clause can filter the cast value. Cases behave as if tried in source order, so `case is APIError` placed before `case let limited as RateLimited` swallows every rate-limit value, and Swift 6.4 does not warn about it. Because `Any` can hold any type, no list of type patterns is provably complete, so the switch needs `default`. The same patterns work outside a switch: `if case let n as Int = value`.

code

swift · 25 lines
swift
class APIError {}
final class RateLimited: APIError {
    let retryAfter: Int
    init(retryAfter: Int) { self.retryAfter = retryAfter }
}

func describe(_ payload: Any) -> String {
    switch payload {
    case let code as Int where code >= 400:
        return "error code \(code)"
    case let code as Int:
        return "code \(code)"
    case let (status, body) as (Int, String):
        return "\(status) with \(body.count) bytes"
    case let limited as RateLimited:
        return "retry after \(limited.retryAfter)s"
    case is APIError:
        return "some API error"
    default:
        return "unknown payload"
    }
}

let payloads: [Any] = [404, 200, (201, "created"), RateLimited(retryAfter: 30), APIError(), 3.5]
for payload in payloads { print(describe(payload)) }

go deeper

for a junior

Recall that is checks a type without binding, as binds the cast value, and a switch over Any always ends with default.

for a middle

Explain that both patterns test the runtime type including subclasses, that as can wrap a tuple pattern or take a where clause, and why order decides which case wins.

for a senior

Order subclass cases before superclass cases, knowing Swift will not warn when a broad case swallows a narrow one, and keep the default observable so unexpected payload types surface.

for a principal

Question long switches over Any in review: they often stand in for a protocol requirement or an enum of payloads that the compiler could check exhaustively.

## What the two patterns check Swift has two **type-casting patterns**. Both look at the **runtime type** of the value being matched — the type of what is actually stored, not the static type of the variable — and both succeed for that exact type **or any subclass** of it. | Pattern | Matches when | Binds | |---|---|---| | `is T` | The runtime type is `T` or a subclass of `T` | Nothing; the cast result is discarded | | `let x as T` | Same condition | `x`, already cast to type `T` | | `let (a, b) as (Int, String)` | The value is a tuple of those element types | `a` and `b`, destructured | The reference manual describes `is` as behaving like the `is` operator and `as` as casting the matched value to the pattern on its left. Both are most often used when the control value has type `Any` — a decoded payload, a notification's user info value, a heterogeneous array — and the code has to branch on what it actually holds. ## Composing `as` with other patterns The `as` pattern is written `pattern as Type`, so the left side can be any pattern: - a binding: `case let code as Int:`; - a tuple of bindings: `case let (status, body) as (Int, String):`; - combined with `where`: `case let code as Int where code >= 400:` — the cast happens first, then the condition runs on the `Int`, and a false condition moves matching on to the next case; - in a compound case, as long as every pattern binds the same names with the same types. An `as` pattern is a **cast, not a conversion**. A `String` holding `"404"` never matches `case let code as Int`; turning text into a number is a separate call to the failable `Int(_:)` initializer. The reference manual says the `is` pattern appears only in `switch` case labels, but the Swift 6.4 compiler also accepts `if case is Int = value` and `if case let n as Int = value`; the compiler's behaviour is what ships. ## Order: specific before general Matching behaves as if cases are tried in source order, and the first match wins. With a class hierarchy that has `RateLimited` as a subclass of `APIError`: 1. `case is APIError:` placed first matches every `RateLimited` value too, because a subclass instance passes the superclass test. 2. A later `case let limited as RateLimited:` is then never reached. 3. When the control value has type `Any`, Swift 6.4 compiles that ordering **without a warning** — nothing tells you the second case is dead. The fix is mechanical: list subclasses before superclasses, and the most constrained `where` cases before the unconstrained case for the same type, as with `code >= 400` above a plain `Int` case. ## Exhaustiveness over `Any` and over a class `Any` can hold a value of any type, including types that do not exist yet, so a `switch` over `Any` is never provably exhaustive by type patterns alone and needs `default`. When the control value is statically a class type instead, the picture changes: in a switch over an `APIError` value, `case is APIError` covers everything, the switch is exhaustive without `default`, and Swift warns `'is' test is always true`. Any case after it is unreachable. ## Patterns versus casts outside a switch `case let x as T` performs the same conditional cast as `if let x = value as? T`. The pattern form earns its place when one `switch` tries several types in order with one shared fallback; a single test reads better as `as?`. The cast operators themselves, including `as!`, and the bridging rules for Foundation types belong with the Swift material on casting and metatypes; here the subject is how they behave inside patterns. ## Review checklist - Subclass cases above superclass cases, every time. - A `default` that surfaces the unexpected type, by logging it or failing loudly in debug builds, rather than a silent `break`. - No `as` pattern expected to parse or convert values. - A long `switch` over `Any` questioned: often a protocol requirement or an enum of payload cases would let the compiler check exhaustiveness instead of relying on runtime types.

  • If a Swift switch's control value is statically an APIError rather than Any, does it still need default?
    No. `case is APIError` then matches every possible value, so the switch is exhaustive without `default`, and Swift 6.4 warns `'is' test is always true`. A later `case is RateLimited` becomes unreachable, so subclass cases go first and the superclass case acts as the catch-all.
  • Does case let code as Int match a String such as "404" stored in an Any?
    No. An `as` pattern is a dynamic cast: it succeeds only when the stored value really is an `Int`. Turning text into a number is a separate, failable `Int(_:)` call that you make explicitly before or instead of the switch.
  • How does case let x as T in a Swift switch relate to if let x = value as? T?
    Both perform the same conditional cast. The pattern form lets one `switch` try several types in order and share one `default`; `as?` produces an `Optional` for a single test. Which casts succeed at all, including bridging to Foundation types, is the same rule in both forms.

  • case is RateLimited still wins after case is APIError, because it is more specific.
  • Swift warns when a superclass case shadows a subclass case in a switch over Any.
  • case let code as Int converts a numeric String into an Int.
  • A switch over Any is exhaustive once it lists every type the code expects.
  • case is T binds the cast value for use in the case body.