一、模式(Pattern)
- 什么是模式?
- 模式是用于匹配的规则,比如switch的case、不做错误的catch等
- Swift中的模式有
- 通配符模式(Wildcard Pattern)
- 标志符模式(Identifier Pattern)
- 值绑定模式(Value-Binding Pattern)
- 元组模式(Tuple Pattern)
- 枚举Case模式(Enumeration Case Pattern)
- 可选模式(Optional Pattern)
- 类型转换模式(Type-Casting Pattern)
- 表达式模式(Expression Pattern)
二、通配符模式(Wildcard Pattern)
- _ 匹配任何值
- _?匹配非nil值
enum Life {
case human(name: String, age: Int?)
case animal(name: String, age: Int?)
}
func check(_ life: Life) {
switch life {
case .human(let name, age: _):
print("human", name)
case .animal(let name, age: _?):
print("animal", name)
default:
print("other")
}
}
check(.human(name: "Haha", age: 20)) // human Haha
check(.human(name: "JJJ", age: nil)) // human JJJ
check(.animal(name: "Cat", age: nil)) // other
三、标志符模式(Identifier Pattern)
- 给对应的变量、常量赋值
var age = 10
let name = "JJJ"
四、值绑定模式(Value-Binding Pattern)
- 值绑定
let point = (2, 0)
switch point {
case (_, 0 ):
print("1234000")
case let (_, y):
print("33333333", y)
}
五、元组模式(Tuple Pattern)
- 元组
let points = [(2, 0), (2, 1),(2, 2)]
for(x, _) in points {
print(x)
}
六、枚举Case模式(Enumeration Case Pattern)
- if case 语句等价于只有1个case的switch语句
var age = 2
// 原来的写法
if age >= 0 && age <= 9 {
print("[0...9]")
}
// case模式,“=” 意思是匹配
if case 0...9 = age {
print("[0...9]")
}
guard case 0...9 = age else { return }
print("[0...9]")
- switch写法
switch age {
case 0...9: print("[0...9]")
default: break
}
// 元组的for case匹配
let points = [(1, 0), (2, 1),(3, 0)]
for case let (x, 0) in points {
print(x)
} // 1, 3
七、可选模式(Optional Pattern)
- 可选模式
let height: Int? = 10
if case .some(let x) = height {
print("height1 = ", x)
}
if case let x? = height {
print("height2 = ", x)
}
if let x = height {
print("height3 = ", x)
}
let heights: [Int?] = [nil, 2, 3, nil, 5]
for case let x? in heights {
print("x = ", x)
}
// 等价于上面的
for height in heights {
if let x = height {
print(x)
}
}
八、类型转换模式(Type-Casting Pattern)
- 类型转换
var num: Any = 2
switch num {
case is Int:
// 编译器依然认为num是Any类型
print("( is Int)", num)
// 如果需要转Int、需要用下面的👇🏻
//case let n as Int:
// print("as Int, \(n + 1)")
default:
print("other")
}
九、表达式模式(Expression Pattern)
- 表达式
let point = (2, 0)
switch point {
case (0, 0 ):
print("(0,0) is at the origin)")
case (-2...2, -2...2):
print("point.0 =", point.0, "point.1 =",point.1)
default:
print("other")
}
- 自定义模式一
struct Student {
var score = 0, name = ""
// switch 在判定时调用了~=运算符
static func ~= (pattern: Int, value: Student) -> Bool {
value.score >= pattern
}
static func ~=(pattern: ClosedRange<Int>, value: Student) -> Bool {
pattern.contains(value.score)
}
static func ~=(pattern: Range<Int>, value: Student) -> Bool {
pattern.contains(value.score)
}
}
var stu = Student(score: 75, name: "JJJ")
switch stu {
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90]]")
case 60...79: print("[60, 79]]")
case 0: print(">= 0")
default:break
}
- 自定义模式二
extension String {
static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
pattern(value)
}
}
func hasPrefix(_ prefix: String) -> ((String) -> Bool) { { $0.hasPrefix(prefix) } }
func hasSuffix(_ suffix: String) -> ((String) -> Bool) { { $0.hasSuffix(suffix) } }
var str = "JJJ"
switch str {
case hasPrefix("j"), hasSuffix("J"):
print("以j开头、以J结尾")
default:
break
}
- 自定义表达式三
// 偶数
func isEven(_ i: Int) -> Bool {
i % 2 == 0
}
// 奇数
func isOdd(_ i: Int) -> Bool { i % 2 != 0 }
extension Int {
// pattern: (Int) -> Bool,接收的是一个Int的value
static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
pattern(value)
}
}
var age = 9
switch age {
// 匹配(Int) -> Bool 这样的表达式
case isEven:
print("偶数")
case isOdd:
print("奇数")
default:
print("其他")
}
// 写法升级,
// 可以把 isEven、isOdd这样的写法换成 ~> 这样
// 自定义表达式
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
//
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { { $0 > i } }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { { $0 >= i } }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { { $0 < i } }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { { $0 <= i } }
var num = 0
switch num {
// 匹配(Int) -> Bool 这样的表达式
case ~<=10 where num>0:
print("大于0,小于10")
case ~>10:
print("大于10")
default:
print("其他")
}
至此Swift的模式匹配基本涵盖,有不足之处还请各位大佬批准指正,不胜感激!!!







网友评论