How to do if pattern matching with multiple cases?

后端 未结 3 1502
一整个雨季
一整个雨季 2020-12-06 10:20

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, Fem         


        
相关标签:
3条回答
  • 2020-12-06 10:36

    For pattern matching, what you describe will not work yet. You could do this in your case. But if it cannot be convert into a hashValue. Then this would not work either.

    // Using Pattern Matching for more than one case.
    if case 0...2 = a.hashValue {
        print("Hello")
    }
    
    //Normal if else
    if a == .Male || a == .Female {
        print("Hello")
    }
    
    0 讨论(0)
  • 2020-12-06 10:48

    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) {
    
    }
    
    0 讨论(0)
  • 2020-12-06 10:54

    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.

    0 讨论(0)
提交回复
热议问题