gpt4 book ai didi

swift - 我如何在 Swift 4 中测试具有关联值的枚举案例的等效性

转载 作者:搜寻专家 更新时间:2023-10-30 23:04:33 24 4
gpt4 key购买 nike

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

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(以及相应的测试),那么代码将按预期工作。

看起来过去人们决定使用运算符重载来解决这个问题:How to test equality of Swift enums with associated values .但是现在我们有了 Swift 4,我想知道是否有更好的方法?或者是否有更改使链接的解决方案无效?

谢谢!

最佳答案

Swift 提案

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

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

因此就足够了

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

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

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

编译器将合成一个合适的==操作符。

关于swift - 我如何在 Swift 4 中测试具有关联值的枚举案例的等效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com