简体   繁体   English

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

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

I would like to test the equivalency of a couple variables of enumeration types, like this: 我想测试枚举类型的几个变量的等效性,如下所示:

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.

Sadly, these all produce this errors like this one: 可悲的是,这些都会产生这样的错误:

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.
~~ ^  ~~

Translation: If your enumeration uses associated values, you can't test it for equivalency. 翻译:如果您的枚举使用关联的值,则无法测试它的等效性。

Note: If .aMoreComplexCase (and the corresponding tests) were removed, then the code would work as expected. 注意:如果.aMoreComplexCase (和相应的测试),则代码将按预期工作。

It looks like in the past people have decided to use operator overloading to get around this: How to test equality of Swift enums with associated values . 看起来过去人们已经决定使用运算符重载来解决此问题: 如何使用关联值测试Swift枚举的相等性 But now that we have Swift 4, I wonder if there is a better way? 但是现在有了Swift 4,我想知道是否有更好的方法? Or if there have been changes that make the linked solution invalid? 还是发生了使链接的解决方案无效的更改?

Thanks! 谢谢!

The Swift proposal 迅捷的建议

has been accepted and implemented in Swift 4.1 (Xcode 9.3): 已在Swift 4.1 (Xcode 9.3)中接受并实现:

... synthesize conformance to Equatable/Hashable if all of its members are Equatable/Hashable. ...如果其所有成员都是平等/可哈希的,则综合符合平等/可哈希的要求。

therefore it suffices to 因此,足以

... opt-in to automatic synthesis by declaring their type as Equatable or Hashable without implementing any of their requirements. ...通过将其类型声明为Equatable或Hashable来选择自动综合,而无需实现其任何要求。

In your example – since String is Equatable – it will suffice to declare 在您的示例中-由于StringEquatable足以声明

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

and the compiler will synthesize a suitable == operator. 然后编译器将合成一个合适的==运算符。

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

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