How to Check a Class Type in a Swift Switch Statement

Written by

in

Quick answer: Swift’s switch is pattern matching, so case is Circle: and case let c as Circle: are valid patterns. Order cases from the most specific subclass to the most general superclass, and add a default branch, because the compiler cannot prove that is patterns cover every type.

Why this happens

Swift’s switch is a pattern-matching statement, not a value comparison. Every case is a pattern, and one of the pattern kinds is the type-casting pattern: is Type and as Type. That means is works inside switch exactly the way it works inside if.

The confusion usually comes from two places. First, most languages only allow constant comparison in a switch, so people assume case is Circle: is illegal and fall back to a long if / else if chain. Second, the canonical example of is inside a switch appears in the “Type Casting for Any and AnyObject” chapter of The Swift Programming Language, which makes it look like a feature that only applies to Any.

It applies to any type. The only real constraints are that the compiler cannot prove exhaustiveness from is patterns, so a default branch is required, and that cases are evaluated top to bottom, so a superclass case placed first will swallow every subclass below it.

How to fix it

1. Use case is Type: for a plain check

If you only need to know which type you have, is is enough. No binding, no cast.

class Shape {}
class Circle: Shape {}
class Square: Shape {}

func describe(_ shape: Shape) -> String {
    switch shape {
    case is Circle:
        return "circle"
    case is Square:
        return "square"
    default:
        return "some other shape"
    }
}

Writing the bare type name, case Circle:, is not valid pattern syntax. The is keyword is what turns the type into a pattern.

2. Bind the matched value with case let x as Type

Most of the time you want the object typed correctly inside the branch. case let x as Type both tests and downcasts in one step, so no force cast is needed.

class Circle: Shape {
    var radius: Double = 1
}

func area(_ shape: Shape) -> Double {
    switch shape {
    case let circle as Circle:
        return .pi * circle.radius * circle.radius
    default:
        return 0
    }
}

Inside that branch, circle is a real Circle, not a Shape. If you don’t need the name, case is Circle: is the shorter form.

3. Match several types in one case with commas

A comma between patterns behaves like ||. This is handy when several types share the same handling.

func describe(_ value: Any) -> String {
    switch value {
    case is Int, is String:
        // either type lands here
        return value is Int ? "integer \(value)" : "string \(value)"
    default:
        return "\(value)"
    }
}

Note that case is Int matches any integer, while case 0 as Int matches only the value zero. The as form is an expression pattern with a cast; the is form is a pure type test.

4. Order cases from most specific to most general

This is the mistake that produces silently wrong behaviour rather than a compiler error. The first matching case wins, and a subclass instance also matches its superclass.

// Wrong: Circle is a Shape, so the first case catches everything
switch shape {
case is Shape:
    print("shape")
case is Circle:
    print("circle")   // unreachable
}

// Right: narrowest type first
switch shape {
case is Circle:
    print("circle")
case is Shape:
    print("shape")
}

Swift will warn you when a cast can never succeed, for example Cast from 'Shape' to unrelated type 'String' always fails, but it will not warn you about an unreachable subclass case.

5. Add where for extra conditions

A type match can be refined with a where clause, which keeps the logic inside the switch instead of nesting an if.

switch shape {
case let circle as Circle where circle.radius > 10:
    print("large circle")
case is Circle:
    print("small circle")
case is Square:
    print("square")
case is Shape:
    print("other shape")
}

6. Expect Switch must be exhaustive

The compiler reasons about enum cases, not about class hierarchies. Even if you list every subclass you know about, it still wants a fallback.

switch shape {
case is Circle:
    print("circle")
case is Square:
    print("square")
// error: Switch must be exhaustive
}

Add default: (or a final case is Shape: if you want to be explicit about the base type). If you genuinely want the compiler to enforce coverage, model the variants as an enum with associated values instead of a class hierarchy — switch over an enum is checked for exhaustiveness.

7. Consider not switching on types at all

Type switching is a code smell when the behaviour belongs to the type. If every branch calls a method that the object could implement itself, move it into the class or a protocol requirement and let dynamic dispatch do the work.

protocol Shape {
    func area() -> Double
}

struct Circle: Shape {
    let radius: Double
    func area() -> Double { .pi * radius * radius }
}

Then shapes.map { $0.area() } replaces the whole switch. Keep case is for the cases where you genuinely cannot add behaviour to the type — third-party classes, Any values coming out of JSON, or heterogeneous collections.

A metatype switch such as switch type(of: shape) { case is Circle.Type: ... } also compiles, but it reads worse and gains nothing over case let circle as Circle.

How to prevent it

  • Put subclass cases above superclass cases; treat the order as part of the logic, not formatting.
  • Always include a default branch when matching with is — the compiler cannot prove coverage.
  • Prefer case let x as Type over case is Type plus a force cast inside the branch.
  • Use where clauses instead of nesting if statements inside a case body.
  • If you find yourself listing every subclass, convert the hierarchy to an enum with associated values so exhaustiveness is checked for you.
  • Keep type switching at the boundary of your code (parsing, bridging) and out of core logic.

FAQ

Can I use is inside a Swift switch case?

Yes. case is SomeType: is a standard type-casting pattern and works for classes, structs, protocols and Any. It behaves identically to if value is SomeType.

Why does my switch say Switch must be exhaustive when I covered every subclass?

The compiler does not analyse class hierarchies to prove that is patterns cover all possibilities. Add a default branch, or switch over an enum with associated values if you want the compiler to verify coverage.

Does the order of cases matter when matching class types?

Yes. Cases are tested top to bottom and the first match wins. A subclass instance also matches its superclass, so a case is Shape: placed before case is Circle: makes the circle branch unreachable — with no warning from the compiler.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.