Swift
Beginner
1 min read
Pattern Matching
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)")
}