Swift学习笔记23-模式匹配

张开发
2026/6/5 14:28:22 15 分钟阅读
Swift学习笔记23-模式匹配
// // main.swift // class23模式(Pattern) // // Created by sakiko on 2026/4/8. // import Foundation print(Hello, World!) //模式就是用于匹配的规则如switch的case,捕捉错误的catch、ifguardwhilefor等等 /* Swift中的模式 1.通配符模式(wildcard pattern) 2.标识符模式(Identifier pattern) 3.值绑定模式(Value-Binding Pattern) 4.元组模式(Tuple Pattern) 5.枚举Case模式(Enumeration Case Pattern) 6.可选模式(Optional Pattern) 7.类型转换模式(Type-Casting Pattern) 8.表达式模式(Expression Pattern) */ //1.通配符模式_用于匹配任何值_? 用于匹配非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, _): //_表示不关心这个值具体是什么 print(human,name) case .animal(let name, _?)://_?表示不关心这个值但是这个值一定不能是nil print(animal, name) default: print(other) } } check(.human(name: Rose, age: 20))//human Rose check(.human(name: Jack, age: nil))//human Jack check(.animal(name: Dog, age: 5))//animal Dog check(.animal(name: Cat, age: nil))//other(因为另一个值不能是nil所以只能到default了) //2.标识符模式(Identifier Pattern):给对应的变量、常量名赋值 var age 10 let name Jack //3.值绑定模式:把值绑定到常量/变量上 let point (3, 2) switch point { //把 point 的值绑定到 x 和 y 这两个变量上。 case let (x, y): print(The point is at\(x),\(y)).) } //4.元组模式 let points [(0, 0),(1, 0), (2, 0)] for (x, _) in points { print(x) } let name1: String? jack let age1 18 let info: Any [1, 2] switch (name1, age1, info) { case (_?, _ , _ as String): //用as看看是不是都是字符串符合就输出case不是就输出default print(case) default: print(default) } var scores [jack : 98, rose : 100, kate: 86] for(name, score) in scores { print(name1, score) } //rose 100 kate 86 jack 98 //5.枚举Case模式: if case语句等价于只有1个case的switch语句 //这是↓原来的写法 func case_intro() { let ages 2 if ages 0 ages 9 { print([0, 9]) } //这是↓用枚举Case模式的 if case 0...9 ages { print([0, 9]) } // ↓这个和上面两个也是一个效果guard必须要和return一起用所以都是在函数里的。 guard case 0...9 ages else { return print([0, 9]) } switch ages { case 0...9: print([0, 9]) default: break } let ages2: [Int?] [2, 3, nil, 5] for case nil in ages2 { print(有nil值) break } let points [(1, 0), (2, 1), (3, 0)] for case let (x, 0) in points { print(x)//返回的是1 3 } } case_intro() //这两行不知道为啥报错 //guard 是 Swift 中用来进行条件检查的一种控制流语句。它的主要目的是确保某个条件为真否则就会提前退出当前作用域通常用于保证某些条件成立以便代码的后续执行。 //6.可选模式(Optional Pattern) let age3: Int? 42 if case .some(let x ) age3 { print(x) }//42 let age4: [Int?] [nil, 2, 3, nil, 5] for case let age4? in age4 { print(age4)//2,3,5 } //↑↓这两段是等价的 let age5: [Int?] [nil, 2, 3, nil, 5] for item in age5 { if let age5 item { print(age5) } } func check(_ num: Int?) { switch num { case 2?: print(2) case 4?: print(4) case 6?: print(6) case _?: print(other) //可选项是整数但不符合以上三种情况就出other case _: print(nil)//不是Int就输出nil } } check(4)//4 check(8)//other check(nil)//nil //7.类型转换模式 let num: Any 6 //默认数据类型由所赋值的类型决定,但这里表示数据类型可以是任何(Any) switch num { case is Int: //这个模式检查 num 是否为 Int 类型。如果是执行相应的代码块。 print(is Int, num) //case let n as Int: //print(as Int, n 1) //该模式用于将 num 强制转换为 Int 类型并绑定到变量 n。这样你可以在后续的代码中使用 n 进行更复杂的操作比如给 n 加1。(这里表示可以这样操作但是在这个知识点上不是必要的) default: break }//is Int 6 class Animal { func eat(){print(type(of: self),eat)} } class Dog: Animal { func run() {print(type(of: self), run)}} class Cat: Animal { func jump(){ print(type(of: self), run)}} func check(_ animal: Animal) { switch animal { case let dog as Dog: //这里使用了 类型转换将 animal 强制转换为 Dog 类型并赋值给变量 dog。如果 animal 的实际类型确实是 Dog则执行这个块中的代码可以调用 dog.eat() 和 dog.run() 方法。 dog.eat() dog.run() case is Cat: //这个模式检查 animal 是否为 Cat 类型。它并不进行强制转换只是简单判断. animal.eat() default : break } } check(Dog()) //Dog eat Dog run check(Cat()) //Cat eat //这个部分我感觉懂了80%没全懂 //8.表达式模式:主要是用于 switch 语句中根据某个值的状态或内容来选择执行的逻辑。 //表达式模式用在case中 let point1 (1, 2) switch point1 { case (0, 0): print((0, 0) is at the origin.) case (-2...2, -2...2): print((\(point1.0),\(point1.1)) is near the origin.) default: print(The point is at (\(point1.0), \(point1.1)).) } //(1,2) is near the origin. //自定义表达式模式:可以通过重载运算符自定义表达式模式的匹配规则 struct Student{ var score 0, name static func ~ (pattern: Int, value: Student) - Bool { value.score pattern } static func ~ (pattern: ClosedRangeInt, value: Student) - Bool { pattern.contains(value.score) } static func ~ (pattern: RangeInt, value: Student) - Bool { pattern.contains(value.score) } } var stu Student(score: 75, name: Jack) 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 } //[60, 79] if case 60 stu{ print(60) } var info1 (Student(score: 70, name: Jack),及格) switch info1 { case let(60, text): print(text) default: break } //及格 //自定义表达式模式举例2:其实我看不太懂在干啥 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 jack switch str { case hasPrefix(j), hasSuffix(k): print(以j开头以k结尾) default: break } //以j开头以k结尾 //自定义表达式模式举例3 func isEven(_ i: Int) - Bool { i % 2 0} func isOdd(_ i: Int) - Bool {i % 2 ! 0 } extension Int { static func ~ (pattern: (Int) - Bool, value: Int) - Bool { pattern(value) } } var ageq 9 switch ageq { case isEven: print(偶数) case isOdd: print(奇数) default: break } 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 age0 9 switch age0 { case ~0: print(1) case ~10: print(2) default: break } //1 //where:可以使用where为模式匹配增加匹配条件 var data (10, Jack) switch data { case let (age, _) where age 10: print(data.1, age10) case let (age, _) where age 0: print(data.1, age0) default: break } var age123 [10, 20, 44, 23, 55] for age in age123 where age 30 { print(age) }//44 55 protocol Stackable { associatedtype Element} //associatedtype为某个类型提供占位符名称。实现该协议的具体类型需要指定这个占位符的实际类型。 protocol Container { associatedtype Stack : Stackable where Stack.Element : Equatable } func equalS1: Stackable, S2: Stackable(_ s1: S1, _ s2: S2) - Bool where S1.Element S2.Element, S1.Element : Hashable { return false } extension Container where Self.Stack.Element : Hashable { }

更多文章