SyntaxStudy
Sign Up
Swift Beginner 1 min read

Pattern Matching

Swift's switch statement supports powerful pattern matching: value patterns, range patterns, tuple patterns, type-casting patterns, and where clauses for additional conditions. The if case and guard case syntax extends pattern matching beyond switch statements. This is especially useful with enums that have associated values. Swift 5.9 introduced if and switch expressions, allowing them to be used directly as values in assignments.
Example
// Tuple pattern matching
let point = (2, 0)
switch point {
case (0, 0):          print("Origin")
case (let x, 0):      print("On x-axis at \(x)")
case (0, let y):      print("On y-axis at \(y)")
case (let x, let y):  print("At (\(x), \(y))")
}

// Where clause
let value = 42
switch value {
case let n where n < 0:   print("Negative")
case let n where n == 0:  print("Zero")
case let n where n > 0:   print("Positive: \(n)")
default: break
}

// if case with associated values
enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
}

let shape = Shape.circle(radius: 5.0)
if case .circle(let r) = shape {
    print("Circle area: \(Double.pi * r * r)")
}

// for case
let shapes: [Shape] = [.circle(radius: 3), .rectangle(width: 4, height: 5), .circle(radius: 1)]
for case .circle(let r) in shapes {
    print("Circle with radius \(r)")
}