Swift 中的 switch
语句非常强大,支持模式匹配、范围匹配、元组、枚举关联值等多种用法。以下是一些常见且实用的例子:
1. 基础用法:匹配具体值 #
let fruit = "apple"
switch fruit {
case "apple":
print("It's an apple!")
case "banana":
print("It's a banana!")
default:
print("Unknown fruit")
}
// 输出:It's an apple!
2. 范围匹配(Range Matching) #
let score = 85
switch score {
case 0..<60:
print("不及格")
case 60..<80:
print("及格")
case 80...100:
print("优秀")
default:
print("无效分数")
}
// 输出:优秀
3. 元组(Tuple)匹配 #
let point = (x: 3, y: 2)
switch point {
case (0, 0):
print("原点")
case (_, 0):
print("在 x 轴上")
case (0, _):
print("在 y 轴上")
case (-2...2, -2...2):
print("在 4x4 的区域内")
default:
print("其他位置")
}
// 输出:在 4x4 的区域内
4. 枚举(Enum)匹配 #
普通枚举: #
enum Direction {
case north, south, east, west
}
let dir = Direction.north
switch dir {
case .north:
print("向北")
case .south:
print("向南")
case .east:
print("向东")
case .west:
print("向西")
}
// 输出:向北
带关联值的枚举: #
enum NetworkResponse {
case success(code: Int, data: String)
case failure(error: String)
}
let response = NetworkResponse.success(code: 200, data: "数据加载成功")
switch response {
case .success(let code, let data) where code == 200:
print("成功:\(data)")
case .success(let code, _):
print("其他状态码:\(code)")
case .failure(let error):
print("失败:\(error)")
}
// 输出:成功:数据加载成功
5. 使用 where
子句过滤条件
#
let number = 7
switch number {
case let x where x % 2 == 0:
print("\(x) 是偶数")
case let x where x % 2 != 0:
print("\(x) 是奇数")
default:
break // 不会执行到这里
}
// 输出:7 是奇数
6. 值绑定(Value Binding) #
let value: Any = 42
switch value {
case let str as String:
print("字符串:\(str)")
case let num as Int where num > 0:
print("正整数:\(num)")
case let num as Int:
print("其他整数:\(num)")
default:
print("未知类型")
}
// 输出:正整数:42
7. 使用 fallthrough
继续执行下一个 case
#
let num = 5
switch num {
case 5:
print("是 5")
fallthrough
case 6:
print("继续执行到 6 的 case")
default:
print("其他")
}
// 输出:
// 是 5
// 继续执行到 6 的 case
8. 结合 guard
提前退出
#
func checkValue(_ value: Int?) {
switch value {
case .none:
print("值为 nil")
case .some(let val) where val < 0:
print("值不能为负数")
case .some(let val):
guard val > 100 else { return }
print("值超过 100: \(val)")
}
}
checkValue(150) // 输出:值超过 100: 150
checkValue(50) // 无输出(guard 提前退出)
9. 匹配可选类型(Optional) #
let optionalValue: Int? = 10
switch optionalValue {
case .some(let value):
print("有值:\(value)")
case .none:
print("无值")
}
// 输出:有值:10
10. 模式匹配 + 类型检查 #
let mixedValue: Any = "Hello"
switch mixedValue {
case is Int:
print("这是一个整数")
case let str as String where str.count > 5:
print("长字符串:\(str)")
case let str as String:
print("短字符串:\(str)")
default:
print("未知类型")
}
// 输出:短字符串:Hello
总结 #
Swift 的 switch
支持以下特性:
- 模式匹配:匹配值、范围、元组、枚举等。
- 值绑定:用
let
或var
提取值。 - 条件过滤:通过
where
子句添加额外条件。 - 类型检查:结合
is
和as
操作符。 - 可选类型支持:直接处理
.some
和.none
。
这些特性使得 switch
在 Swift 中比许多其他语言更灵活和强大!