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 {}
网友评论