← thecodex.expert · The Codex Family of Knowledge
Swift

Pattern Matching

Checking just ONE enum case doesn’t require a full switch with an else branch — if case handles exactly that single-pattern situation directly, reading far more naturally than a switch would for the same job.

Swift 6 if case: one pattern, no full switch Last verified:
Canonical Definition

if case pattern = value { ... } checks a single pattern, an alternative to a full switch when only one case actually matters — guard case works the same way for an early-exit style. Tuple patterns let switch match multiple values at once, with underscore (_) as a wildcard for positions that don't matter. A where clause attaches an additional boolean condition directly to a case, letting a single case handle both a structural match AND a value-based condition together, rather than needing a nested if inside the case body.

if case: checking a single pattern

No full switch or else branch needed — if case reads directly as "if this specific pattern matches," which is exactly the situation when only one case out of several actually needs handling right now.

Swiftif_case.swift
enum Status {
    case active(since: Int)
    case inactive
}

let status = Status.active(since: 2020)

if case .active(let year) = status {
    print("Active since \(year)")
}   // no else needed — this is checking ONE specific pattern, not exhausting every case

Tuple patterns with wildcards

The underscore in each case ignores that position entirely — (0, _) matches any y-coordinate as long as x is exactly 0, letting the pattern express "on the y-axis" concisely.

Swifttuple_patterns.swift
let point = (0, 5)

switch point {
case (0, 0):
    print("Origin")
case (0, _):
    print("On the y-axis")   // matches — x is 0, y can be anything
case (_, 0):
    print("On the x-axis")
default:
    print("Somewhere else")
}

where: an extra condition on a case

where attaches a genuine boolean condition directly to the case — this case only matches if BOTH the pattern matches AND the where condition is true, avoiding a separate nested if inside the case body.

Swiftwhere_clause.swift
let temperature = 105

switch temperature {
case let t where t > 100:
    print("Dangerously hot: \(t)")
case let t where t < 32:
    print("Freezing: \(t)")
default:
    print("Normal range")
}

Sources

1
Apple / Swift.org. The Swift Programming Language, "Patterns," docs.swift.org/swift-book.