Swift之where一般使用场景
使用where语句之前必须在where之前有一个主语变量名
- 协议约束
//基类A继承了SomeProtocol协议才能添加扩展
extension SomeProtocol where Self: A {
func showParamA() {
print(self.a)
}
}
- for...in...遍历
let arr = [1, 2, 4, 5, 6]
for (index, value) in arr.enumerated() where value > 4 {
print(index, value)
}
- case 语句,相当于if判断
let arr = [1, 2, 4, 5, 6]
for (index, value) in arr.enumerated() where value > 4 {
switch value {
case let a where a < 6:
print(index)
default:
print(value)
}
}
- if let 和 guard中,在swift4.0版本以后,使用逗号代替where
let str : String? = "hello"
if let value = str, value.count == 5 {
print(value)
}
guard let value = str, value.count == 5 else { return }
print(value)
posted on 2020-03-08 12:18 东方🐺 阅读(1129) 评论(0) 编辑 收藏 举报