[英]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來選擇自動綜合,而無需實現其任何要求。
在您的示例中-由於String
是Equatable
足以聲明
enum AnEnumeration: Equatable {
case aSimpleCase
case anotherSimpleCase
case aMoreComplexCase(String)
}
然后編譯器將合成一個合適的==
運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.