Match Swift Patterns with Arrays

Curious if there is a way in Swift to do the following:

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 that there are other ways that I could make this contrived example, for example, case 4, 5, 6: or not use the switch, and use bar.contains(value) instead, but I'm looking for a solution specifically related to matching pattern templates to an array. Thanks!

+5
source share
2 answers

You can define a custom pattern corresponding to the ~= operator, which takes an array as a "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 already exist, for example, for intervals:

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

What 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") } 
+14
source

All Articles