Benjamin Herzog Benjamin Herzog - 1 year ago 68
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 Source

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

if ([Gender.Male, Gender.Female].includes(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: :D

EDIT: This is the Swift version:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download