我想测试两个Swift枚举值的相等性。例如:
- enum SimpleToken {
- case Name(String)
- case Number(Int)
- }
- let t1 = SimpleToken.Number(123)
- let t2 = SimpleToken.Number(123)
- XCTAssert(t1 == t2)
但是,编译器不会编译等式表达式:
- error: could not find an overload for '==' that accepts the supplied arguments
- XCTAssert(t1 == t2)
- ^~~~~~~~~~~~~~~~~~~
我有做定义自己的等于运算符的重载吗?我希望Swift编译器能够自动处理它,就像Scala和Ocaml做的一样。
正如其他人所指出的,Swift不会自动合成必要的相等运算符。让我提议一个更清洁(IMHO)的实施:
- enum SimpleToken: Equatable {
- case Name(String)
- case Number(Int)
- }
- public func ==(lhs: SimpleToken,rhs: SimpleToken) -> Bool {
- switch (lhs,rhs) {
- case (.Name(let a),.Name(let b)) where a == b: return true
- case (.Number(let a),.Number(let b)) where a == b: return true
- default: return false
- }
- }
它远非理想 – 有很多重复 – 但至少你不需要做内嵌的if语句的嵌套开关。