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<S>(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: "")
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift官方文档的词汇结构中, 有非常多的关键字, 它们被用于声明中、语句中、表达式中、类中、模式中, 还有以数...
    小宇宙_fly阅读 884评论 0 3
  • 在一些Swift开源库里经常能看到 where 关键字的使用,但是查找开发文档的时候又找不到这个关键字。为了方便使...
    枫叶1234阅读 2,316评论 0 0
  • 在一些Swift开源库里经常能看到 where 关键字的使用,但是查找apple帮助文档的时候又找不到这个关键字,...
    DelegateChai阅读 10,047评论 3 24
  • Swift 中有多少关键字? 在Swift官方文档的词汇结构中, 有非常多的关键字, 它们被用于声明中、语句中、表...
    超级卡布达阅读 1,757评论 0 2
  • 作者:Jordan Morgan,原文链接,原文日期:2017-02-11 译者:郑一一;校对:numbbbbb,...
    iOS亮子阅读 706评论 0 1

友情链接更多精彩内容