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 {
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 {
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") }
enumeration swift swift-playground
Dominique vial
source share