如何在没有原始类型的情况下比较两个枚举实例



给定:

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

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

实现枚举的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
            }
        }
    }       
}

最新更新