美文网首页
Swift之where关键字使用

Swift之where关键字使用

作者: loongod | 来源:发表于2022-06-14 10:58 被阅读0次

其实总结一句话,就是在各种环境下添加约束

一、switch语句中

    enum Person {
        case man(name: String, age: Int)
        case women(name: String, age: Int)
    }
------
        let p = Person.man(name: "loong", age: 30)
        
        switch p {
        case let .man(name, age) where age > 25:
            print("peron: \(name), age > 25")
        default:
            print("default")
        }
------console
peron: loong, age > 25

二、for-in语句中

        let arrayOne = [1, 2, 3, 4, 5]
        let dictionary = [1: "v1", 2: "v2"]
        for i in arrayOne where dictionary[i] != nil {
            print("i: \(i)")
        }
---console
i: 1
i: 2

三、do-catch语句中

enum ExceptionError:Error{
    case httpCode(Int)
}
func throwError() throws {
    throw ExceptionError.httpCode(500)
}
------
do {
    try throwError()
} catch ExceptionError.httpCode(let httpCode) where httpCode >= 500 {
    print("server error")
}

四、Protocol约束

protocol SampleProtocol { }
extension SampleProtocol where Self: UILabel {
    // 只给遵守SampleProtocol协议的UILabel添加了拓展
    func getString() -> String {
        return self.text ?? ""
    }

}

extension UIView: SampleProtocol {   }
------
        // 如果是UIView的话,调用不了getString扩展方法
        let label = UILabel(frame: CGRect.zero)
        label.text = "hello, world"
        let text = label.getString()
        print("label text: \(text)")
---console
label text: hello, world

五、泛型约束

类型约束:指定类型参数必须继承自特定的类、遵守某个协议或协议组合。

    func addMember<T>(a: T) where T: SampleProtocol {
        
    }
    // 简约写法
    func addValue<T: AnyObject>(a: T) {
        
    }

相关文章

  • Swift where 关键字

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

  • Swift之where关键字使用

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

  • 控制语句

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

  • Swift where 关键字

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

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

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

  • Swift where关键字的使用

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

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

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

  • 【SQL基础】二:筛选数据

    关键字: where、like 简单使用:select cola from tableA where cola ...

  • 24. Swift学习之where关键字

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

  • Swift 关键字 -- where

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

网友评论

      本文标题:Swift之where关键字使用

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