SwiftWhen
SwiftWhen 是一个实验性的 µ框架,试图模拟 Kotlin 的 when 表达式。
这得益于 函数构建器,Swift 5.1 中提出的一个新特性。
集成
Cocoapods
将以下行添加到您的 Podfile
pod 'SwiftWhen', '~> 0.1.0'
Swift Package Manager
在您的 Package.swift
文件中将 SwiftWhen 声明为一个依赖
.package(url: "https://github.com/shackley/SwiftWhen", from: "0.1.0")
使用说明
when
可用作简洁的 switch 语句的替代。
let x = 2
when(x) {
1 => print("x is 1")
2 => print("x is 2")
3 => print("x is 3")
}
// x is 2
由于 when
是一个函数,它可以用作表达式。
let x = 2
let result = when(x) {
1 => "x is 1"
2 => "x is 2"
3 => "x is 3"
}
print(result)
// x is 2
通过使用闭包执行多个语句。
let x = 2
when(x) {
1 => {
print("x is 1")
foo()
}
2 => {
print("x is 2")
bar()
}
}
// x is 2
如果需要以相同方式处理多个情况,您可以使用一个数组将它们合并。
let x = 2
when(x) {
[1, 3, 5] => print("x is 1, 3, or 5")
[2, 4, 6] => print("x is 2, 4, or 6")
}
// x is 2, 4, or 6
使用 otherwise
关键字来处理未知的情况。
let x = 5
when(x) {
1 => print("x is 1")
2 => print("x is 2")
otherwise => print("x is something else")
}
// x is something else
when
也可以与范围一起使用。
let x = 15
when(x) {
0 ..< 10 => print("x is between 0 and 9")
10 ..< 20 => print("x is between 10 and 19")
20 ... 30 => print("x is between 20 and 30")
otherwise => print("x is something else")
}
// x is between 10 and 19
when
也可以不带任何参数使用。这它将作为一个简单的 if-else 链,其中条件是布尔表达式。选择第一个为真的表达式。
let x = 5
when {
x == 1 => print("x is 1")
x == 5 => print("x is 5")
otherwise => print("x is something else")
}
// x is 5
注意事项
由于 when
仅仅是一个函数,而不是 Swift 语言的真正特性,因此无法在编译时进行完备性检查。如果一个 when 表达式不包含匹配的情况,则在运行时将发生 fatalError
。