Switch Statement trong Swift (Pattern Matching)
1. Switch cơ bản
let day = 3
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Other day")
}Lưu ý: Swift không cần break, không có fallthrough mặc định!
2. Multiple Values
let day = 6
switch day {
case 1, 2, 3, 4, 5:
print("Weekday")
case 6, 7:
print("Weekend")
default:
print("Invalid")
}3. Ranges
let score = 85
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
case 50..<70:
print("D")
default:
print("F")
}4. Tuples
let point = (0, 0)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On x-axis")
case (0, _):
print("On y-axis")
default:
print("Somewhere else")
}5. Value Binding
let point = (2, 0)
switch point {
case (let x, 0):
print("On x-axis at x = \(x)")
case (0, let y):
print("On y-axis at y = \(y)")
case let (x, y):
print("At (\(x), \(y))")
}6. Where clause
let point = (1, 1)
switch point {
case let (x, y) where x == y:
print("On diagonal")
case let (x, y) where x == -y:
print("On anti-diagonal")
default:
print("Off diagonal")
}7. Enum với Switch
enum Direction {
case north, south, east, west
}
let direction = Direction.north
switch direction {
case .north:
print("Go north")
case .south:
print("Go south")
case .east:
print("Go east")
case .west:
print("Go west")
}8. Fallthrough
let number = 5
switch number {
case 5:
print("Five")
fallthrough // Tiếp tục case tiếp theo
case 4, 6:
print("Near five")
default:
break
}9. So sánh với Kotlin
| Swift | Kotlin | Ghi chú |
|---|---|---|
switch x { } | when (x) { } | Tương tự |
case 1, 2: | 1, 2 -> | Multiple values |
case 90...100: | in 90..100 -> | Ranges |
default: | else -> | Default case |
Không cần break | Không cần break | Giống nhau |
📝 Tóm tắt
switch- Pattern matching mạnh mẽ- Không cần
break(không fallthrough) default:bắt buộc (trừ enum exhaustive)- Hỗ trợ ranges, tuples, value binding
whereclause cho điều kiện phức tạpfallthroughđể tiếp tục case tiếp theo
Last updated on
Swift