Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do if pattern matching with multiple cases?

Tags:

swift

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 {

}
like image 219
Ben Avatar asked Sep 05 '16 15:09

Ben


People also ask

What is one way to implement pattern matching on methods?

The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Try the following example program, which matches a value against patterns of different types.

Which method of case class allows using objects in pattern matching?

Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.

How does pattern matching work?

Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.

What are the different ways to implement match expressions in scala?

Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }


2 Answers

A simple array does the trick:

if [.Male, .Female].contains(a) {
    print("Male or female")
} else {
    print("Transgender")
}

I'm simply amazed at Swift's ability to infer type. Here, it gets that .Male and .Female are of type gender from a.

like image 117
Code Different Avatar answered Oct 21 '22 03:10

Code Different


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: https://stackoverflow.com/a/25391725/607033 :D

EDIT: This is the Swift version:

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

}
like image 26
inf3rno Avatar answered Oct 21 '22 04:10

inf3rno