Pattern Matching in Depth

Identifier/value binding case let x:, case (let a, var b): case (0, _): case.success(let value):

case let x?:, case.some(let x):, case nil: case let s as String:, case is Int: Expression (~=) case 1...5:, case "a"..."f": where clause case let x where x > 10:

// if case / guard case / for case
let results: [Result<Int, Error>] = [.success(1), .failure(URLError(.badURL)), .success(3)]
for case .success(let value) in results { print(value) }        // 1, 3
if case .failure(let error) = results[1] { print(error) }

let optionals: [Int?] = [1, nil, 3]
for case let n? in optionals { print(n) }                       // 1, 3

// Custom ~= operator
struct Regexish { let prefix: String }
func ~= (pattern: Regexish, value: String) -> Bool { value.hasPrefix(pattern.prefix) }
switch "SwiftUI" {
case Regexish(prefix: "Swift"): print("Swift-related")
default: break
}

// Nested and multiple patterns
enum Shape { case circle(radius: Double), rect(w: Double, h: Double) }
let pairs: [(Shape, String)] = [(.circle(radius: 1), "a"), (.rect(w: 2, h: 3), "b")]
for case (.rect(let w, let h), let label) in pairs where w < h { print(label, w, h) }

switch (Int("5"), Int("x")) {
case let (a?, b?): print(a + b)
case (let a?, nil), (nil, let a?): print("only \(a)")
case (nil, nil): print("none")
}