本文介绍了比较枚举与Swift中的相关值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于带有关联值的枚举,Swift不提供相等运算符。所以我实现了一个能够比较两个枚举:

For enums with associated values, Swift doesn't provide the equality operator. 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
    }
}

我的问题是我有很多这样的枚举很多情况下,所以我需要写很多这个比较代码(对于每个枚举,对于每一种情况)。

正如你可以看到,这个代码总是遵循相同的方案,所以似乎有一个更抽象的方式来实现比较行为。有办法解决这个问题吗?例如与泛型?

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)

这篇关于比较枚举与Swift中的相关值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:31