Swift之where关键字使用

2022-06-14  本文已影响0人  loongod

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

一、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) {
        
    }
上一篇下一篇

猜你喜欢

热点阅读