如何将两个枚举实例与NO原始类型进行比较?

时间:2017-04-26 04:45:37

标签: swift enums

假设:

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

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

如何使这项工作?

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

请注意,我无法放弃自定义枚举(它不能包含原始值)

1 个答案:

答案 0 :(得分:1)

为您的枚举实施Equatable协议。

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
            }
        }
    }       
}