> ## 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.

# Swift Switch Statement

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.

```swift theme={"dark"}
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.

```swift theme={"dark"}
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.

```swift theme={"dark"}
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.

```swift theme={"dark"}
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.

```swift theme={"dark"}
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.

```swift theme={"dark"}
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`.

```swift theme={"dark"}
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
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
