Swift语法-where关键字详解
来源:互联网 发布:迅雷已死 知乎 编辑:程序博客网 时间:2024/05/22 14:41
在Swift语法里where关键字的作用跟SQL的where一样, 即附加条件判断。
1、 在集合遍历时使用where, 条件为真时执行代码块, 为假时不执行代码块。
let array = [0, 1, 2, 3, 4, 5, 6] //使用switch遍历 array.forEach { switch $0 { case let x where x > 3: //where相当于判断条件 print("后半段") default: print("默认值") } } //使用for in遍历 for value in array where value > 2 { print(value) //输出3 4 5 6 } for (index, value) in array.enumerated() where index > 2 && value > 3 { print("下标:\(index), 值:\(value)") }
输出:
默认值默认值默认值默认值后半段后半段后半段3456下标:4, 值:4下标:5, 值:5下标:6, 值:6
2、在补充异常的do/catch里使用
3、 协议使用where, 只有基类实现了当前协议才能添加扩展。 换个说法, 多个类实现了同一个协议,该语法根据类名分别为这些类添加扩展, 注意是分别(以类名区分)!!!
protocol SomeProtocol { func someMethod()}class A: SomeProtocol { let a = 1 func someMethod() { print("call someMethod") }}class B { let a = 2}//基类A继承了SomeProtocol协议才能添加扩展extension SomeProtocol where Self: A { func showParamA() { print(self.a) }}//反例,不符合where条件extension SomeProtocol where Self: B { func showParamA() { print(self.a) }}let objA = A()let objB = B() //类B没实现SomeProtocol, 所有没有协议方法objA.showParamA() //输出1
小结: where关键字可以用在集合遍历、switch/case、协议中; Swift3时if let和guard场景的where已经被Swift4的逗号取代, 例如 if let a=param, a>10(前者需要判断是否为nil,后者相当于where条件)
阅读全文
0 0
- Swift语法-where关键字详解
- Swift where关键字的使用
- Swift语法—— where语句使用
- 12.Swift 中的关键字详解
- C++ 语法 : volatile关键字详解
- Swift语法基础:18 - Swift的元组, 绑定值, Where
- iOS开发之Swift基本语法详解
- Swift 基本语法详解(1)
- Swift 基本语法详解(2)
- 3.Swift 中的where
- swift switch tuple where
- swift关键字
- Swift 关键字
- Swift 关键字
- where 关键字用法
- swift语法
- Swift语法
- Swift语法
- 【兴趣书签】时间与量子
- mysql数据库备份策略及应用场景
- 欢迎使用CSDN-markdown编辑器
- 从入职时间长短剖析离职原因
- "Windows is not genuine" error in Windows 7 or Windows Server 2008 R2
- Swift语法-where关键字详解
- No dashboards are active for the current data set. 解决tensorboard无法启动和显示问题(pycharm启动)
- requests.get为什么得到的内容和查看源文件不一样?
- yum install 提示 except OSError, e: ^ SyntaxError: invalid syntax
- 服务器数据库等杂项
- linux下tomcat,jdk完整安装
- 'ascii' codec can't decode byte 0xef in position 0:ordinal not in range(128)错误解决与原理分析
- CentOs 安装java环境
- Spring Cloud (12) | Spring Cloud Zuul网关调用微服务,request请求参数是application/json