3

I have the following enum:

enum Message: ErrorType {
    case MessageWithInfo(info:String?)
    case MessageDidFail
    case MessageDidSend(info:String)
    case InvalidMessageData
    case MessageWithDelay(delay:Double)
    .... will keep adding more
}

I am trying to figure out how to write the Equatable function that would let me then compare Message enums.

I found some similar questions on stack overflow, but I couldn't find one that would allow me to compare without having to switch on every single case.

Is there a way to write the equatable function once and have it work even if I keep adding more cases to this enum?

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • 1
    For enums with associated values you have to implement the == yourself explicitly. That means that you have to switch on every possible case. I don't think there is a way around it. – Martin R Nov 06 '15 at 22:22
  • 2
    Possible duplicate of [How to test equality of Swift enums with associated values](http://stackoverflow.com/questions/24339807/how-to-test-equality-of-swift-enums-with-associated-values). – Martin R Nov 06 '15 at 22:24

1 Answers1

5

It is not possible write one function that will work for all enums with all kinds of cases. Which basically is what you want.

The reason is discusses here. The second answer shows a method that can be used with enums that have a rawValue.

This is because an Enum of mixed types loses it's rawValue.

You can write a switch to get a rawValue (you have to ignore the associated values). But this can't be done automatically.

With a Struct or Class you also can not write a method that automatically creates a sequence/set of all the var's let's declared in it. Just like an Enum is not able to make a sequence/set out of it's cases.

enum Message: ErrorType {

    case MessageWithInfo(info:String?)
    case MessageDidFail
    case MessageDidSend(info:String)
    case InvalidMessageData
    case MessageWithDelay(delay:Double)

    var rawValue : Int {
        get {
            switch self {
            case .MessageWithInfo(info: _) : return 0
            case .MessageDidFail : return 1
            case .MessageDidSend(info: _) : return 2
            case .InvalidMessageData : return 3
            case .MessageWithDelay(delay: _) : return 4

            }
        }
    }
}

func ==(lhs:Message,rhs:Message) -> Bool {

    return (lhs.rawValue == rhs.rawValue)

}
Community
  • 1
  • 1
R Menke
  • 8,183
  • 4
  • 35
  • 63