I face a problem using enumeration I can't understand.
Here is declaration of an enumeration type:
enum SomeType {
case un
case deux
case trois
}
Then I want to match an individual enumeration values with a if statement:
var testValue: SomeType = .trois
if testValue == .trois {
// Do something
}
Everything is fine!
Now I want to add an associated value only to the first member value:
enum SomeType {
case un(Int)
case deux
case trois
}
var testValue: SomeType = .trois
if testValue == .trois {
// Do something
}
An error than appear on the if statement: Could not find member 'trois'
Does this mean enumerations can only be matched using a switchstatement?
Precisions
What I want to achieve is: "Does testValue is of member value of 'trois' with no consideration for associated value". In others words, how to match an enumeration on member value only.
Here a solution implementing Airspeed Velocity answers:
// 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")
}