@Martin R 为什么只停留在数组上呢?所有符合Sequence协议的类型都有一个contains
实例方法。以下代码与您的答案具有相同的行为,但它适用于符合Sequence
的任何类型。
func ~=<S : Sequence>(sequence: S, value: S.Element) -> Bool
where S.Element: Equatable {
return sequence.contains(value)
}
let items = [1, 2, 3, 4, 5]
let iterable = items.makeIterator()
let value = 3
switch value {
case iterable:
print("\(value) is contained in iterable")
default:
print("\(value) is NOT contained in iterable")
}
然而,我们可以做得更好
我认为case iterable
太神奇了。它没有传达我们正在测试value
在iterable
中的成员身份这一事实。如果我们能写case containedIn(iterable)
会更好。实际上,这是可能的:
public func ~=<T>(pattern: (T) -> Bool, value: T) -> Bool {
return pattern(value)
}
func containedIn<S : Sequence>(_ sequence: S) -> ((S.Element) -> Bool)
where S.Element: Equatable {
return { element in sequence.contains(element) }
}
let arrayOfNumbers = [1, 2, 3, 4, 5]
let setOfNumbers: Set = [5, 6, 7, 8, 9, 10]
let value = 8
switch value {
case containedIn(arrayOfNumbers):
print("\(value) is contained in arrayOfNumbers")
case containedIn(setOfNumbers):
print("\(value) is contained in setOfNumbers")
default:
break
}
唯一的问题是,当在 switch 语句的上下文之外使用
containedIn
时,它的行为会出现意外情况。