简体   繁体   English

将枚举与Swift中的关联值进行比较

[英]Compare enums with associated values in Swift

For enums with associated values, Swift doesn't provide the equality operator. 对于具有关联值的枚举,Swift不提供相等运算符。 So I implemented one to be able to compare two enums: 所以我实现了一个能够比较两个枚举:

enum ExampleEnum{
     case Case1
     case Case2(Int)
     case Case3(String)
     ...
}

func ==(lhs: ExampleEnum, rhs: ExampleEnum) -> Bool {

    switch(lhs, rhs){
    case (.Case1, .Case1): return true
    case let (.Case2(l), .Case2(r)): return l == r
    case let (.Case3(l), .Case3(r)): return l == r
    ...
    default: return false
    }
}

My problem is that I have a lot of such enums with a lot of cases so I need to write a lot of this comparison code (for every enum, for every case). 我的问题是我有很多这样的枚举有很多案例所以我需要编写很多这样的比较代码(对于每个枚举,对于每种情况)。

As you can see, this code always follows the same scheme, so there seems to be a more abstract way to implement the comparison behavior. 如您所见,此代码始终遵循相同的方案,因此似乎有一种更抽象的方式来实现比较行为。 Is there a way to solve this problem? 有没有办法解决这个问题? For example with generics? 例如泛型?

Currently there is no way of achieving this without writing out all the cases, we can hope that it'll be possible in a later version. 目前没有办法在没有写出所有案例的情况下实现这一目标,我们希望在以后的版本中可以实现。

If you really have a lot of cases and you don't want to write them all out, you can write a small function that generates the code automatically for you (I've been doing this just recently for something that wasn't possible to refactor) 如果你真的有很多案例并且你不想全部写出来,你可以编写一个小函数来自动为你生成代码(我最近一直在这样做,因为这是不可能的。重构)

As of Swift 4.2 just add Equatable protocol conformance. 从Swift 4.2开始,只需添加Equatable协议一致性。 It will be implemented automatically. 它将自动实施。

enum ExampleEquatableEnum: Equatable {
    case case1
    case case2(Int)
    case case3(String)
}

print("ExampleEquatableEnum.case2(2) == ExampleEquatableEnum.case2(2) is \(ExampleEquatableEnum.case2(2) == ExampleEquatableEnum.case2(2))")
print("ExampleEquatableEnum.case2(1) == ExampleEquatableEnum.case2(2) is \(ExampleEquatableEnum.case2(1) == ExampleEquatableEnum.case2(2))")

Ie default comparison takes associated values in account. 即默认比较采用帐户中的相关值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM