switch 模式匹配
switch 穷举/无穿透、区间匹配、元组匹配、where 子句
switch 模式匹配
Swift 的 switch 极其强大——不需要 break(不会穿透)、可以匹配区间/元组、where 添加条件。
学完本章你将: 掌握 switch 穷举、区间/元组匹配、where 子句。
基本 switch
swift
let char: Character = "a"
switch char {
case "a", "A": // 多个值
print("字母 A")
case "b"..."z": // 区间匹配
print("小写字母")
default:
print("其他")
}
// switch 必须穷举所有情况——否则编译错误
元组匹配
swift
let point = (0, 5)
switch point {
case (0, 0):
print("原点")
case (_, 0):
print("在 x 轴上") // _ 匹配任意值
case (0, _):
print("在 y 轴上") // 输出这个
case (-2...2, -2...2):
print("在原点附近")
default:
print("其他位置")
}
where 子句
swift
let number = 15
switch number {
case let x where x % 2 == 0:
print("偶数: \(x)")
case let x where x % 3 == 0:
print("3 的倍数: \(x)") // 输出
default:
print(number)
}