Powerful switch with pattern matching
Write expressive switches: match associated values, ranges, tuples, and add where-clauses. Keep branches exhaustive and readable.
Why pattern matching?
Swift switch matches patterns: enums with payloads, numeric ranges, tuples, and where conditions. It is also exhaustive.
Associated values
Bind associated values using let/var directly in the case pattern.
enum Network {
case success(code: Int, body: String)
case failure(message: String)
case offline
}
let r1: Network = .success(code: 200, body: "OK")
switch r1 {
case .success(let code, let body):
print("success", code, body)
case .failure(let msg):
print("fail:", msg)
case .offline:
print("offline")
}All lessons in this course
- Enums with Power basics
- Powerful switch with pattern matching
- Finite state modeling