美文网首页Swift
24. Swift学习之where关键字

24. Swift学习之where关键字

作者: YungFan | 来源:发表于2018-11-22 09:46 被阅读81次

在Swift中很多地方都是用到了一个关键字where,这个关键字的含义和数据库中的where差不多,用于条件筛选(条件过滤),where 关键字在 Swift 中非常强大,那么在Swift中哪些地方用到了这个关键字呢?下面来总结一下。

一、 switch case中

let names = ["王小二","张三","李四","王五"]
for name in names {
    switch name {
    case let x where x.hasPrefix("王"):
        print("姓王的有:\(x)")
    default:
        print("你好,\(name)")
    }
}

二、for循环中

let array = [0,1,2,3,4,5,6,7,8,9]
for value in array where value % 2 == 0 {
    print(value)
}

三、protocol协议中

protocol SomeProtocol{
    
}
extension SomeProtocol where Self:UIView{
    //只给遵守myProtocol协议的UIView添加了拓展
    func getInfo() -> String{
        return "属于UIView类型"
    }
}
extension UIButton:SomeProtocol{}
UIButton().getInfo()

四、Generic 泛型中


protocol AnOthorProtocol {
    func say()
}
struct Bird: AnOthorProtocol {
    func say() {
        print("Hello World")
    }
    
}
func genericFunc<T>(num: T) where T: AnOthorProtocol {
    print(num)
}
genericFunc(num: Bird())

五、do catch异常处理中

enum ExceptionError:Error{
    case httpCode(Int)
}
func throwError() throws {
    throw ExceptionError.httpCode(404)
}
do{
    try throwError()
}catch ExceptionError.httpCode(let httpCode) where httpCode == 404{
    print("not found error")
}

相关文章

  • 24. Swift学习之where关键字

    在Swift中很多地方都是用到了一个关键字where,这个关键字的含义和数据库中的where差不多,用于条件筛选(...

  • 【Swift 3 && C++11】<第一

    |Swift|C++:-:|:-:|:-:有用的关键字和符号|<>, where|template,<> 先来介绍...

  • Swift where 关键字

    1、关键字定义 在Swift语法里where关键字的作用跟SQL的where一样, 即附加条件判断。 2、使用方式...

  • Swift 知识点2: 那些容易被遗忘的关键字

    1.where:在Swift语法里where关键字的作用跟SQL的where一样,条件语句 2.final:防止重...

  • Swift之where关键字使用

    其实总结一句话,就是在各种环境下添加约束。 一、switch语句中 二、for-in语句中 三、do-catch语...

  • Swift where 关键字

    在一些Swift开源库里经常能看到 where 关键字的使用,但是查找apple帮助文档的时候又找不到这个关键字,...

  • Swift 关键字 -- where

    Where switch for loop do catch protocol 与 where结合部分 与范型结合

  • 控制语句

    if语句 switch swift不需要加break跳出 区间匹配 元祖匹配 case中还可以使用where关键字...

  • Swift where关键字的使用

    在一些Swift开源库里经常能看到 where 关键字的使用,但是查找开发文档的时候又找不到这个关键字。为了方便使...

  • swift之mutating关键字

    部分参考:swift之mutating关键字 swift中在structures和enumerations的方法中...

网友评论

    本文标题:24. Swift学习之where关键字

    本文链接:https://www.haomeiwen.com/subject/xtvkqqtx.html