Swift之where關鍵字使用

其實總結一句話,就是在各種環境下添加約束

一、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) {
        
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章