使用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)

相关文章:

  • 2021-11-20
  • 2021-12-25
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2022-01-28
猜你喜欢
  • 2021-10-11
  • 2021-07-18
  • 2022-12-23
  • 2021-08-02
  • 2021-12-24
  • 2021-12-09
  • 2021-09-20
相关资源
相似解决方案