Frankie Frankie - 4 months ago 21
iOS Question

Swift switch pattern matching with arrays

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!

Answer

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("5 is in foo")
case bar:
    print("5 is in bar")
default:
    break
}

Similar operators exist already e.g. for intervals:

public func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool