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)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM