如何在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.
注意:如果删除了.aMoreComplexCase
(和相应的测试),则代码将按预期工作.
Note: If .aMoreComplexCase
(and the corresponding tests) were removed, then the code would work as expected.
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.
在您的示例中-因为String
是Equatable
–声明
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屋!