【问题标题】:Swift enums with arguments: how to compare them?带参数的 Swift 枚举:如何比较它们?
【发布时间】:2015-11-06 22:12:42
【问题描述】:

我有以下枚举:

enum Message: ErrorType {
    case MessageWithInfo(info:String?)
    case MessageDidFail
    case MessageDidSend(info:String)
    case InvalidMessageData
    case MessageWithDelay(delay:Double)
    .... will keep adding more
}

我正在尝试弄清楚如何编写 Equatable 函数,然后让我比较 Message 枚举。

我发现了一些关于堆栈溢出的类似问题,但我找不到一个可以让我在不必打开每个案例的情况下进行比较的问题。

有没有办法编写一次 equatable 函数并让它工作,即使我不断向这个枚举添加更多案例?

【问题讨论】:

标签: swift enums equatable


【解决方案1】:

不可能编写一个适用于所有枚举类型的函数。这基本上就是你想要的。

原因是讨论here。第二个答案显示了一种可用于具有 rawValue 的枚举的方法。

这是因为混合类型的 Enum 失去了它的 rawValue。

您可以编写一个开关来获取 rawValue(您必须忽略关联的值)。但这不能自动完成。

使用 Struct 或 Class,您也不能编写自动创建所有 var 的序列/集合的方法,让我们在其中声明。就像 Enum 无法从它的案例中创建序列/集合一样。

enum Message: ErrorType {

    case MessageWithInfo(info:String?)
    case MessageDidFail
    case MessageDidSend(info:String)
    case InvalidMessageData
    case MessageWithDelay(delay:Double)

    var rawValue : Int {
        get {
            switch self {
            case .MessageWithInfo(info: _) : return 0
            case .MessageDidFail : return 1
            case .MessageDidSend(info: _) : return 2
            case .InvalidMessageData : return 3
            case .MessageWithDelay(delay: _) : return 4

            }
        }
    }
}

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

    return (lhs.rawValue == rhs.rawValue)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2017-01-09
    相关资源
    最近更新 更多