I\'m testing this in the Playground and I\'m not sure how to do this. With a normal enum that doesn\'t have associated values, everything is fine.
enum Compa
Enumerations are automatically Equatable
when they have a raw value that's Equatable
. In your first case, the raw value is assumed to be Int
, but it would work if you'd given it another specific type like UInt32
or even String
.
Once you add an associated value, however, this automatic conformance with Equatable
doesn't happen any more, since you can declare this:
let littleNorth = CompassPoint.North(2)
let bigNorth = CompassPoint.North(99999)
Are those equal? How should Swift know? You have to tell it, by declaring the enum
as Equatable
and then implementing the ==
operator:
enum CompassPoint : Equatable {
case North(Int)
case South
case East
case West
}
public func ==(lhs:CompassPoint, rhs:CompassPoint) -> Bool {
switch (lhs, rhs) {
case (.North(let lhsNum), .North(let rhsNum)):
return lhsNum == rhsNum
case (.South, .South): return true
case (.East, .East): return true
case (.West, .West): return true
default: return false
}
}
Now you can test for equality or inequality, like this:
let otherNorth = CompassPoint.North(2)
println(littleNorth == bigNorth) // false
println(littleNorth == otherNorth) // true