看了一些介绍pattern matching的文章,里面有不少种使用用法。总结下来就是两种类型:绑定和判断。模式匹配的起手式是case,这是对传统switch-case的扩展。具体用法如下:
- 「绑定」即let,它表示匹配的数据绑定到变量上。形式是case let (aVar)或case (let aVar)
a. 对变量可以添加where约束条件
b. _ 可以匹配任意数据,但是无法使用
c. case let aVar? 用于匹配可选类型的.some值
d. case let .some(aVar) 用于匹配枚举中的一个枚举值 - 「判断」相当于 ==,它只有true/false结果没有绑定的变量
a. 一种方式是 case is aType
b. 一种方式是case (aVar...bVar) = value,相当于range的contains方法 - ~= 是模式匹配操作符可以通过重载实现自定义模式匹配。系统库提供了range的~=匹配实现
下面是测试用例:
/** 测试数据 */
private let arr = [(1, 1), (2, 4), nil, (1, 3), nil, (2, 2)]
private func optionalMatch() {
for case let item? in arr {
print("optionalMatch: \(item)")
}
}
private func ifMatch() {
for (idx, item) in arr.enumerated() {
// if nil = item
if case let .none = item {
print("ifMatch-optional nil at \(idx)")
} else if case let (1, item)? = item {
print("ifMatch-enum item \(item)")
}
}
}
private func tupleMatch() {
for case let (2, item)? in arr {
if case (_, 2) = (2, item) {
print("tupleMatch-case: \(item)")
} else {
print("tupleMatch-for: \(item)")
}
}
}
private func whereMatch() {
for case let (a, b)? in arr where a == 1 && b > 1 {
print("whereMatch where 1: \(b)")
}
}
private func rangeMatch() {
for case let item? in arr {
if case (2..<3, 3...4) = item {
print("rangeMatch-case, \(item)")
} else if (3...5) ~= item.1 {
// if (3...5).contains(item.)
print("rangeMatch ~=, \(item)")
}
}
}
private func switchMatch() {
for item in arr {
switch item {
case nil:
print("switchMatch nil")
case let (2, b)?:
let subA: Any = b
switch subA {
case let b as Int where b == 4:
print("switchMatch as Type \(item)")
case is Int:
print("switchMatch is Type \(item)")
default:
continue
}
default:
print("switchMatch default \(item)")
}
}
}
/** 自定义匹配方法 */
func ~= (pattern: String, value: Int) -> Bool {
return pattern == "\(value)"
}
private func customMatch() {
for item in arr.compactMap({$0}) {
switch item {
case ("1", "3"):
print("customMatch \(item)")
default:
continue
}
}
}
private let printResult: (() -> ()) -> () = { action in
print()
action()
print()
print("==============================")
}
/** 入口方法 */
func runMatchPatternsDemo() {
printResult(optionalMatch)
printResult(ifMatch)
printResult(tupleMatch)
printResult(whereMatch)
printResult(rangeMatch)
printResult(switchMatch)
printResult(customMatch)
}
运行结果如下:
optionalMatch: (1, 1)
optionalMatch: (2, 4)
optionalMatch: (1, 3)
optionalMatch: (2, 2)
==============================
ifMatch-enum item 1
ifMatch-optional nil at 2
ifMatch-enum item 3
ifMatch-optional nil at 4
==============================
tupleMatch-for: 4
tupleMatch-case: 2
==============================
whereMatch where 1: 3
==============================
rangeMatch-case, (2, 4)
rangeMatch ~=, (1, 3)
==============================
switchMatch default Optional((1, 1))
switchMatch as Type Optional((2, 4))
switchMatch nil
switchMatch default Optional((1, 3))
switchMatch nil
switchMatch is Type Optional((2, 2))
==============================
customMatch (1, 3)
==============================