如何测试Swift枚举与相关值的相等性
发布时间:2020-12-14 06:15:22 所属栏目:百科 来源:网络整理
导读:我想测试两个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 ove
我想测试两个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语句的嵌套开关。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |