繁体   English   中英

如何在Swift 4中测试带有关联值的枚举案例的等价性

[英]How may I test the equivalency of enumeration cases with associated values in Swift 4

我想测试枚举类型的几个变量的等效性,如下所示:

enum AnEnumeration {
  case aSimpleCase
  case anotherSimpleCase
  case aMoreComplexCase(String)
}

let a1 = AnEnumeration.aSimpleCase
let b1 = AnEnumeration.aSimpleCase
a1 == b1 // Should be true.

let a2 = AnEnumeration.aSimpleCase
let b2 = AnEnumeration.anotherSimpleCase
a2 == b2 // Should be false.

let a3 = AnEnumeration.aMoreComplexCase("Hello")
let b3 = AnEnumeration.aMoreComplexCase("Hello")
a3 == b3 // Should be true.

let a4 = AnEnumeration.aMoreComplexCase("Hello")
let b4 = AnEnumeration.aMoreComplexCase("World")
a3 == b3 // Should be false.

可悲的是,这些都会产生这样的错误:

error: MyPlayground.playground:7:4: error: binary operator '==' cannot be applied to two 'AnEnumeration' operands
a1 == b1 // Should be true.
~~ ^  ~~

MyPlayground.playground:7:4: note: binary operator '==' cannot be synthesized for enums with associated values
a1 == b1 // Should be true.
~~ ^  ~~

翻译:如果您的枚举使用关联的值,则无法测试它的等效性。

注意:如果.aMoreComplexCase (和相应的测试),则代码将按预期工作。

看起来过去人们已经决定使用运算符重载来解决此问题: 如何使用关联值测试Swift枚举的相等性 但是现在有了Swift 4,我想知道是否有更好的方法? 还是发生了使链接的解决方案无效的更改?

谢谢!

迅捷的建议

已在Swift 4.1 (Xcode 9.3)中接受并实现:

...如果其所有成员都是平等/可哈希的,则综合符合平等/可哈希的要求。

因此,足以

...通过将其类型声明为Equatable或Hashable来选择自动综合,而无需实现其任何要求。

在您的示例中-由于StringEquatable足以声明

enum AnEnumeration: Equatable {
  case aSimpleCase
  case anotherSimpleCase
  case aMoreComplexCase(String)
}

然后编译器将合成一个合适的==运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM