当前位置: 首页 > news >正文

Swift学习笔记23-模式匹配

// // main.swift // class23模式(Pattern) // // Created by sakiko on 2026/4/8. // import Foundation print("Hello, World!") //模式:就是用于匹配的规则,如switch的case,捕捉错误的catch、if,guard,while,for等等 /* 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: 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: "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, "age>10") case let (age, _) where age > 0: print(data.1, "age>0") 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 equal<S1: 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 { }
http://www.jsqmd.com/news/613972/

相关文章:

  • Win11Debloat:如何让Windows 11重获新生?一个开源工具的全方位解决方案
  • 牛顿插值法实战指南:从差分表构建到Python实现
  • 信创数据库迁移实战:如何将WordPress从MySQL平滑迁移到OpenGauss(附Navicat操作指南)
  • 2026年4月湖南波形梁/波形/W型/防撞/公路/护栏厂家市场全景扫描与优质服务商评估 - 2026年企业推荐榜
  • 2026年山东装修公司抖音推广选购指南:3招教你省钱避坑攻略 - 精选优质企业推荐榜
  • 【Swoole高性能配置黄金法则】:20年老司机亲授8大核心参数调优秘籍,90%开发者都设错了!
  • WarcraftHelper终极指南:让经典魔兽争霸III在现代电脑完美运行
  • 极域电子教室智能解决方案:重新定义教学环境下的自主学习体验
  • Qwen-Image-Edit-2511-Unblur-Upscale效果展示:看AI如何拯救模糊人像
  • LeCroy力科 ADP305 1,400 V 100 MHz 高压差分探头
  • 终极Windows Defender移除指南:3步彻底禁用微软安全组件,性能飙升30%
  • 百达翡丽官方售后服务中心2026年4月最新网点考察实录(含权威验证信息) - 亨得利官方服务中心
  • Asynt平行反应器一级代理/总代理推荐 - 品牌推荐大师
  • 用Qt Creator手把手教你解析BMP文件头:从二进制流到QImage显示的完整流程
  • ComfyUI-WanVideoWrapper:视频生成技术的四维突破与实践指南
  • TegraRcmGUI:3步实现Switch破解的图形化工具全指南
  • 分享 种 .NET 桌面应用程序自动更新解决方案滞
  • OpenCore Legacy Patcher技术揭秘:老Mac升级macOS的底层原理与实战指南
  • 76.Acwing基础课第890题-简单-能被整除的数
  • CACC 协同式自适应巡航模型(仿真软件版本:Carsim2016,Matlab2018b及以上)
  • 5个实用技巧:AI图像处理与隐私保护工具DeepMosaics完全指南
  • 2026年甘肃门禁道闸公司优选 智能化适配 高效售后 贴合本地气候场景 - 深度智识库
  • 局域网内共享远程专用网络
  • 终极免费CAJ转PDF工具:caj2pdf一站式解决方案
  • IDM激活脚本技术指南:从原理到实践的完整解决方案
  • 2026洛阳江浙菜宴请选型指南:3个硬指标避坑清单 - 精选优质企业推荐榜
  • 攻克ControlNet图像异常:3大维度优化实现90%质量提升
  • 通义千问2.5-7B实战部署:从下载到对话,完整步骤详解
  • 2026年腾讯企业邮箱怎么注册申请:从开通到高效使用的完整指南 - 品牌2025
  • 从单体到群体:多 Agent 系统的涌现智能