Error matching enumeration using if statement

I am facing a problem using an enumeration that I cannot understand.

Here is an enumeration type declaration:

enum SomeType { case un case deux case trois } 

Then I want to combine the individual enumeration values ​​with the if :

 var testValue: SomeType = .trois if testValue == .trois { // Do something } 

Everything is good!

Now I want to add the associated value only to the first value of the element:

 enum SomeType { case un(Int) case deux case trois } var testValue: SomeType = .trois if testValue == .trois { // Do something } 

Error in if : Could not find member 'trois' expression

Does this mean that enums can only be matched using the switch ?

Precisions
I want to achieve: "Does testValue have a member value of trois without regard to the associated value." In other words, how to combine enumeration only with the value of a member.

Here the solution that implements Airspeed is:

 // Test equality only on member value func == (lhs:SomeType, rhs:SomeType) -> Bool { switch (lhs, rhs) { case (.un(let lhsNum), .un(let rhsNum)):return true case (.deux, .deux): return true case (.trois, .trois): return true default: return false } } // Test equality on member value AND associated value func === (lhs:SomeType, rhs:SomeType) -> Bool { switch (lhs, rhs) { case (.un(let lhsNum), .un(let rhsNum)) where lhsNum == rhsNum: return true case (.deux, .deux): return true case (.trois, .trois): return true default: return false } } var testValue = SomeType.un(3) // Tests if testValue == .un(1) { println("Same member value") } if testValue === .un(3) { println("Same member value AND same associated contents") } 
+7
enumeration swift swift-playground
source share
1 answer

Enumerations that do not have associated types are automatically equivalent. Enumerations that have associated types are missing. This makes sense because only you can know how the associated type should be handled (for example, the integer that comes with your .un value). Even if .trois does not have an associated type, the lack of equivalence of a freebie affects the entire listing. The switch works slightly differently using pattern matching, so it still works.

If you want your enumeration with the appropriate type to be equivalent, you can define your own == operator:

 enum SomeType { case un(Int) case deux case trois } // possibly there a more succinct way to do this switch func ==(lhs: SomeType, rhs: SomeType) -> Bool { switch (lhs,rhs) { case let (.un(i), .un(j)) where i == j: return true case (.deux,.deux): return true case (.trois, .trois): return true default: return false } } var testValue: SomeType = .trois if testValue == .trois { println("equals .trois") } // note, for SomeType to work with generic // functions that require Equatable, you have // to add that too: extension SomeType: Equatable { } // which means this will work: let a: [SomeType] = [.un(1), .deux, .trois] find(a, .trois) 
+9
source share

All Articles