假设:
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
请注意,我无法放弃自定义枚举(它不能包含原始值)
答案 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
}
}
}
}