Testing for enum value fails if one has associated value?

前端 未结 1 1908
广开言路
广开言路 2020-12-05 11:58

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         


        
相关标签:
1条回答
  • 2020-12-05 12:32

    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
    
    0 讨论(0)
提交回复
热议问题