Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A switch statement evaluates a given control expression and directs program execution to the first matching case block. In Swift, switch statements are strictly evaluated for exhaustiveness, utilize advanced pattern matching, and do not exhibit the implicit fallthrough behavior found in C-based languages.
switch controlExpression {
case pattern1:
    // Statements executed if pattern1 matches
case pattern2, pattern3:
    // Statements executed if pattern2 OR pattern3 matches
default:
    // Statements executed if no preceding patterns match
}

Core Mechanics

Exhaustiveness and @unknown default Swift requires that every possible value of the control expression’s type is accounted for. If the defined case patterns do not cover the entire domain of the type, a default case is mandatory. The compiler will throw an error if a switch is non-exhaustive. When switching over non-frozen enumerations (such as those provided by Apple frameworks or C libraries, which may add new cases in the future), you can use the @unknown default attribute. This acts as a standard default catch-all, but triggers a compiler warning if future enum cases are added and not explicitly handled, helping maintain exhaustiveness over time. No Implicit Fallthrough Execution exits the switch statement immediately after the matched case block finishes executing. You do not need to append a break statement to the end of each case. However, a case block cannot be empty; if you want a case to do nothing, you must use an explicit break. Explicit Fallthrough To replicate C-style cascading execution, you must explicitly declare the fallthrough keyword. This immediately transfers control to the body of the subsequent case block, bypassing that block’s pattern evaluation. While often placed at the end of a case block, fallthrough is not strictly required to be at the lexical bottom and can be nested within conditional logic inside the case.

Pattern Matching Capabilities

Swift’s switch statement extends beyond basic equality checks, supporting several advanced pattern matching techniques. Enumeration Matching Pattern matching against enumeration cases is a primary feature of the switch statement. It allows you to evaluate the specific case of an enum and extract any associated values.
enum NetworkResponse {
    case success(code: Int)
    case failure(error: String)
}

let response = NetworkResponse.success(code: 200)

switch response {
case .success(let code):
    print("Success with status: \(code)")
case .failure(let error):
    print("Failed with error: \(error)")
}
Compound Cases Multiple patterns can be evaluated within a single case by separating them with commas. If any pattern in the list matches the control expression, the case block executes. If a compound case utilizes value bindings, all patterns within that case must include the exact same set of bindings, and each binding must resolve to the same type.
enum Action {
    case move(distance: Int)
    case jump(distance: Int)
    case stop
}

let action = Action.move(distance: 5)

switch action {
case .move(let d), .jump(let d): // Both patterns bind 'd' of type Int
    print("Displaced by \(d)")
case .stop:
    break
}
Interval Matching Cases can evaluate whether a value falls within a specific range using Swift’s closed range (...) or half-open range (..<) operators.
let numericValue = 42

switch numericValue {
case 0..<10:
    print("Single digit")
case 10...99:
    print("Double digit")
default:
    print("Other")
}
Tuple Matching and Wildcards A switch can evaluate multiple values simultaneously using tuples. Each element of the tuple can be tested against a different value or range. The wildcard identifier (_) can be used to match any possible value for a specific tuple element, effectively ignoring it during evaluation.
let coordinate = (1, 0)

switch coordinate {
case (0, 0):
    print("Origin")
case (_, 0):
    print("X-axis")
case (0, _):
    print("Y-axis")
case (-2...2, -2...2):
    print("Within bounds")
default:
    break
}
Value Binding A case can extract matched values (or parts of a matched compound value) and bind them to temporary constants (let) or variables (var). These bindings are scoped exclusively to the body of that specific case block.
let point = (2, 0)

switch point {
case (let x, 0):
    print("On the x-axis with an x value of \(x)")
case (0, let y):
    print("On the y-axis with a y value of \(y)")
case let (x, y):
    print("Somewhere else at \(x), \(y)")
}
where Clauses A case pattern can be appended with a where clause to evaluate an additional boolean condition. The case will only match if both the pattern matches the control expression and the where expression evaluates to true.
let vector = (3, 3)

switch vector {
case let (x, y) where x == y:
    print("Along the identity line")
case let (x, y) where x == -y:
    print("Along the inverse line")
default:
    break
}
Master Swift with Deep Grasping Methodology!Learn More