Swift文法-where關鍵字詳解_Swift基礎

來源:互聯網
上載者:User

        在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條件)





相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.