Benjamin Herzog Benjamin Herzog - 3 months ago 7
Swift Question

How to do if pattern matching with multiple cases?

I'm searching for the syntax to do pattern matching with multiple cases in an if case statement.
The example would be this:

enum Gender {
case Male, Female, Transgender
}

let a = Gender.Male


Now I want to check, if a is .Male OR .Female. But I would like to avoid using switch for this. However the switch statement would be like this:

switch a {
case .Male, .Female:
// do something
}


Is it possible to write this with if case?
I would expect this, but it didn't work :(

if case .Male, .Female = a {

}

Answer

You should use a collection. In JavaScript I would write something like this:

if ([Gender.Male, Gender.Female].includes(actualGender))
    console.log(actualGender);

Note that I have not a clue about swift, or how to do the same in that language, so here is a relevant answer in the topic: http://stackoverflow.com/a/25391725/607033 :D

EDIT: This is the Swift version:

if [.Male, .Female].contains(a) {

}