Swift 关键字 -- where

Where

switch

/// switch 条件语句的判断
///
func whereSwitch(value: (Int, String)) {
    switch value {
    case let (x,y) where x < 60:
        print("\(y)不及格")
    case let (x,y) where x > 90:
        print("\(y)优秀")
    case let (_,y):
        print("\(y)及格")
    }
}

for loop

/// 循环遍历的时候条件判断
///
func whereLoop() {
    let indexs = [1, 2, 3, 4]
    let values = [1: "1", 2: "2"]
    for index in indexs where values[index] != nil {
        print("loop value \(index) - \(String(describing: values[index]))")
    }
   
}

do catch

/// do catch 部分
///
///

class DemoError : Error {
    var code: Int?
    
    init() {
        
    }
}

func whereDoCatch() {
         do {
             let error = DemoError()
             error.code = 500
             throw error
         } catch let e as DemoError where e.code == 500 {
             print("error code 500")
         } catch {
             print("Other error: \(error)")
         }
}

protocol 与 where结合部分

/// where 与协议结合部分
protocol AnimalProtocol {}

class Animal {
    
}

extension AnimalProtocol where Self:Animal {
    func name() -> String {
        return "animal"
    }
}

class Cat: Animal {
    
}

class Dog {
    
}

extension Cat: AnimalProtocol {
    
}

extension Dog: AnimalProtocol {
    
}

func printName() -> Void {
    
    let cat = Cat()
    print(cat.name())
    
    let dog = Dog()
    dog.name() 
    /// 使用报错 -- Referencing instance method 'name()' on 'AnimalProtocol' requires that 'Dog' inherit from 'Animal'
}

与范型结合

/// 与范型结合使用
///
///

class WhereT {
    func printLog() {
        
    }
}

func genericFunction(str:S) where S:WhereT {
    str.printLog()
}

class WhereImp: WhereT {
    
}

func WhereTDemo() -> Void {
    genericFunction(str: WhereImp())
    /// 报错 -- Global function 'genericFunction(str:)' requires that 'String' inherit from 'WhereT'
    genericFunction(str: "")
}

你可能感兴趣的:(Swift 关键字 -- where)