如何在 Swift 4 中测试枚举案例与关联值的等效性

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

提问人:MadEmperorYuri 提问时间:10/17/2017 最后编辑:Martin RMadEmperorYuri 更新时间:4/22/2018 访问量:718

问:

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

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 枚举 运算符 相等 swift4

评论

3赞 Martin R 10/17/2017
这些答案仍然有效。当 github.com/apple/swift-evolution/blob/master/proposals/...被实施时,它会变得更简单。
0赞 MadEmperorYuri 10/17/2017
这就是我需要的。我的代码现在可以正常工作了。也许你应该把这个评论作为一个答案,这样我就可以把它标记为已解决?

答:

6赞 Martin R 10/17/2017 #1

斯威夫特提案

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

...如果 Equatable/Hashable 的所有成员都是 Equatable/Hashable,则合成符合性。

因此,它足以

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

在您的示例中 - 既然是 - 声明就足够了StringEquatable

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

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

评论

1赞 LinusGeffarth 6/6/2018
知道为什么这是选择加入,而不是选择退出吗?
1赞 Martin R 6/6/2018
@LinusGeffarth:在 github.com/apple/swift-evolution/blob/master/proposals/ 中解释。