Enums and Pattern Matching
Where Patterns
Pattern cases can add conditions with where.
Match and filter
where_patterns.swift
Replay: real traced execution (multi-file project)
enum Score {
case points(Int)
}
let value = 82
let score = Score.points(value)
var band = ""
switch score {
case Score.points(let amount) where amount >= 90:
band = "excellent"
case Score.points(let amount) where amount >= 70:
band = "steady"
case Score.points:
band = "practice"
}
print("value=\(value)")
print("band=\(band)")
enum Score {
case points(Int)
}
let value = 45
let score = Score.points(value)
var band = ""
switch score {
case Score.points(let amount) where amount >= 90:
band = "excellent"
case Score.points(let amount) where amount >= 70:
band = "steady"
case Score.points:
band = "practice"
}
print("value=\(value)")
print("band=\(band)")
enum Score {
case points(Int)
}
let value = 95
let score = Score.points(value)
var band = ""
switch score {
case Score.points(let amount) where amount >= 90:
band = "excellent"
case Score.points(let amount) where amount >= 70:
band = "steady"
case Score.points:
band = "practice"
}
print("value=\(value)")
print("band=\(band)")
value ← 82, score ← points(82), band ← (empty)
5let value→ 82 = 82 //@value=45, 956let score→ points(82) = Score.points(value82)7var band→ (empty) = ""switch score
9switch scorepoints(82) {10case Score.points(let amount) where amount >= 90:11 band = "excellent"band ← steady
11 band = "excellent"12case Score.points(let amount82) where amount >= 70:13 band→ steady = "steady"14case Score.points:print("value=\(value)")
18print("value=\(value82)")19print("band=\(bandsteady)")outputvalue=82 band=steady
value ← 45, score ← points(45), band ← (empty)
5let value→ 45 = 456let score→ points(45) = Score.points(value45)7var band→ (empty) = ""switch score
9switch scorepoints(45) {10case Score.points(let amount) where amount >= 90:11 band = "excellent"band ← practice
13 band = "steady"14case Score.points:15 band→ practice = "practice"16}print("value=\(value)")
18print("value=\(value45)")19print("band=\(bandpractice)")outputvalue=45 band=practice
value ← 95, score ← points(95), band ← (empty)
5let value→ 95 = 956let score→ points(95) = Score.points(value95)7var band→ (empty) = ""switch score
9switch scorepoints(95) {10case Score.points(let amount) where amount >= 90:11 band = "excellent"band ← excellent
9switch score {10case Score.points(let amount95) where amount >= 90:11 band→ excellent = "excellent"12case Score.points(let amount) where amount >= 70:print("value=\(value)")
18print("value=\(value95)")19print("band=\(bandexcellent)")outputvalue=95 band=excellent
where
A `where` clause refines a pattern after it has matched the shape of the value.