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