比较嵌套枚举

时间:2016-08-02 21:50:25

标签: swift enums

如果我有

var currentState: TransformState = .Default
enum TransformState {
    case Default
    case Error(ErrorState)

    enum ErrorState {
        case Custom
        case Default
    }
}

var state = TransformState.Error(.Custom)

如何查看是否state == currentState

3 个答案:

答案 0 :(得分:2)

您只需要为Equatable

实施TransformState

TransformState.ErrorState免费获取,因此您可以在实施中使用该事实:

extension TransformState: Equatable {}
func ==(lhs: TransformState, rhs: TransformState) -> Bool {
    switch (lhs, rhs) {
    case (.Default, .Default):
        return true

    case let (.Error(lhsErrorState), .Error(rhsErrorState)):
        return lhsErrorState == rhsErrorState

    default:
        return false
    }
}

请注意,在Swift 3.0中,您可以将操作符重载放在扩展的正文中。

答案 1 :(得分:1)

您的问题与the thread shown by JAL非常相似,因为您的嵌套枚举TransformState. ErrorState是Equatable。

您可以编写自己的==,如:

func == (lhs: TransformState, rhs: TransformState) -> Bool {
    switch (lhs, rhs) {
    case (.Default, .Default):
        return true
    case (.Error(let state1), .Error(let state2)):
        return state1 == state2
    default:
        return false
    }
}
var currentState: TransformState = .Default

var state = TransformState.Error(.Custom)

print(state == currentState) //->false

currentState = .Error(.Custom)
print(state == currentState) //->true

答案 2 :(得分:1)

为您的枚举覆盖==

func ==(lhs: TransformState, rhs: TransformState) -> Bool {
    switch (lhs, rhs) {
    case (.Default, .Default):
        return true

    case (.Error(.Custom), .Error(.Custom)):
        return true

    case (.Error(.Default), .Error(.Default)):
        return true

    default:
        return false
    }
}