我如何在 Swift 4 中测试具有关联值的枚举案例的等效性 [英] How may I test the equivalency of enumeration cases with associated values in Swift 4

查看:29
本文介绍了我如何在 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.

注意:如果删除了 .aMoreComplexCase(和相应的测试),那么代码会按预期工作.

Note: If .aMoreComplexCase (and the corresponding tests) were removed, then the code would work as expected.

过去人们似乎决定使用运算符重载来解决这个问题:如何测试带有关联值的 Swift 枚举的相等性.但是现在我们有了 Swift 4,我想知道是否有更好的方法?或者是否有更改导致链接的解决方案无效?

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. But now that we have Swift 4, I wonder if there is a better way? Or if there have been changes that make the linked solution invalid?

谢谢!

推荐答案

Swift 提案

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

has been accepted and implemented in Swift 4.1 (Xcode 9.3):

... 如果其所有成员都是 Equatable/Hashable,则综合符合 Equatable/Hashable.

... synthesize conformance to Equatable/Hashable if all of its members are Equatable/Hashable.

因此它足够

...通过将它们的类型声明为 Equatable 或 Hashable 而不实现它们的任何要求来选择加入自动合成.

... opt-in to automatic synthesis by declaring their type as Equatable or Hashable without implementing any of their requirements.

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

In your example – since String is Equatable – it will suffice to declare

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

并且编译器会合成一个合适的==操作符.

and the compiler will synthesize a suitable == operator.

这篇关于我如何在 Swift 4 中测试具有关联值的枚举案例的等效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆