2

Given:

enum Example { case Step1 case Step2(data: String)  }

and:

let a: Example = .Step1
let b: Example = .Step2(data: "hi")

how do I make this work?

print(a == b) // ERROR: Binary operator '==' cannot be applied to two 'Example' operands

Note that I can't give up the custom enum (it cannot contain raw values)

gerbil
  • 859
  • 7
  • 26
  • http://stackoverflow.com/questions/31548855/how-to-compare-enum-with-associated-values-by-ignoring-its-associated-value-in-s might also be useful. – rmaddy Apr 26 '17 at 05:00

1 Answers1

1

Implement the Equatable protocol for your enum.

enum Example: Equatable {
    case Step1
    case Step2(data: String)

    static func == (lhs: Example, rhs: Example) -> Bool {
        switch(lhs) {
        case Step1:
            switch(rhs) {
            case Step1:
                return true
            default:
                return false
            }
        case Step2(data: leftString):
            switch(rhs) {
            case Step2(data: rightString):
                return leftString == rightString
            default:
                return false
            }
        }
    }       
}
Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39