好奇如果有办法在Swift中执行以下操作。
let foo = [1, 2, 3]
let bar = [4, 5, 6]
let value = 5
switch value {
case in foo
print("5 is in foo")
case in bar
print("5 is in bar")
default:
break
}
我知道还有其他方法可以使这个人为的例子工作,如case 4, 5, 6:
或不使用开关,而是使用bar.contains(value)
,但我正在寻找一个特别涉及开关模式匹配到阵列的解决方案。谢谢!
您可以定义一个自定义模式匹配运算符~=
,它将数组作为“模式”和值:
func ~=<T : Equatable>(array: [T], value: T) -> Bool {
return array.contains(value)
}
let foo = [1, 2, 3]
let bar = [4, 5, 6]
let value = 5
switch value {
case foo:
print("\(value) is in foo")
case bar:
print("\(value) is in bar")
default:
break
}
已经存在类似的运算符间隔时间:
public func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool
怎么样:
let foo = [1, 2, 3]
let bar = [4, 5, 6]
let value = 5
switch value {
case _ where foo.contains(value):
print("\(value) is in foo")
case _ where bar.contains(value):
print("\(value) is in bar")
default:
print("\(value) is not in foo or bar")
}