Curious if there is a way to do the following in 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
}
I understand there are other ways I could make this contrived example work such as case 4, 5, 6:
or not using a switch and instead using bar.contains(value)
but I'm looking for a solution specifically involving switch pattern matching to an array. Thanks!
我知道还有其他方法可以使这个设计的示例工作,比如情形4、5、6:或者不使用开关,而是使用bar.contains(value),但是我正在寻找一个解决方案,具体涉及到与数组匹配的开关模式。谢谢!
2 个解决方案
#1
17
You could define a custom pattern matching operator ~=
which takes an array as the "pattern" and a 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
}
Similar operators exist already e.g. for intervals:
类似的运算符已经存在,例如间隔:
public func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool
#2
15
How about:
如何:
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")
}
#1
17
You could define a custom pattern matching operator ~=
which takes an array as the "pattern" and a 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
}
Similar operators exist already e.g. for intervals:
类似的运算符已经存在,例如间隔:
public func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool
#2
15
How about:
如何:
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")
}