12

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 CompassPoint {
    case North
    case South
    case East
    case West
}

var direction = CompassPoint.East

if direction != .West {
    println("Go West!")
}

However, if one of my enums has an associated value, the direction test fails with this error: could not find member 'West'

enum CompassPoint {
    case North(Int)
    case South
    case East
    case West
}

var direction = CompassPoint.East

if direction != .West {
    println("Go West!")
}

What can I do to allow for this test?

1 Answer 1

22

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
Sign up to request clarification or add additional context in comments.

2 Comments

The cases returning true can be combined to a single case: case (.South, .South), (.East, .East), (.West, .West): return true
From Swift 4.1 due to SE-0185, Swift also supports synthesizing Equatable and Hashable for enums with associated values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.