Swift switch pattern matching with arrays
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
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")
}