Swift中where的使用場景

Swift中可以使用where對模式匹配增加進一步的匹配條件。常見的5種使用場景:swiftch語句、for循環語句、協議中關聯類型的約束、函數的適用條件、擴展中。

func testWhere() {
    // 1.
    var data = (20, "dandy")
    switch data {
    case let(age, _) where age > 10: // where給case增加條件
        print(data.1, "age > 10")
    default: break
    }
    // 2.
    var ages = [10, 20, 30, 40]
    for age in ages where age > 30 {
        print(age)
    }// 40
    
}

// 3.
protocol Stackable { associatedtype Element }
protocol Container {
    associatedtype Stack: Stackable where Stack.Element: Equatable // 關聯類型的元素要遵守Equatable協議
}

// 4.
func equal<S1: Stackable, S2: Stackable>(_ s1: S1, s2: S2) -> Bool
    where S1.Element == S2.Element, S1.Element: Hashable {
        return false
}

//5
extension Container where Self.Stack.Element: Hashable {}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章