枚举可以在Swift中包含另一个枚举值吗?

时间:2016-11-17 21:39:08

标签: swift enums

我想分享一些枚举属性。类似的东西:

enum State {
  case started
  case succeeded
  case failed
}

enum ActionState {
  include State // what could that be?
  case cancelled
}

class Action {
  var state: ActionState = .started

  func set(state: State) {
    self.state = state
  }

  func cancel() {
    self.state = .cancelled
  }
}

我知道为什么ActionState无法从State继承(因为状态cancelledState中没有任何代表),但我仍希望能够说&# 34; ActionState就像具有更多选项的State,ActionState可以获得State类型的输入,因为它们也是ActionState"

类型

我知道如何使用上述逻辑来复制ActionState中的案例并在set函数中进行切换。但我正在寻找更好的方法。

我知道枚举无法在Swift中继承,我已经阅读了swift-enum-inheritance的协议答案。它没有解决继承"的问题。或者包括来自另一个枚举的案例,但只包括属性和变量。

1 个答案:

答案 0 :(得分:13)

详细

  • Swift 4,3
  • Xcode 10.2.1(10E1001),Swift 5(本文最后修订)

解决方案

enum State {
    case started, succeeded, failed
}

enum ActionState {
    case state(value: State), cancelled
}

class Action {
    var state: ActionState = .state(value: .started)
    func set(state: State) { self.state = .state(value: state) }
    func cancel() { state = .cancelled }
}

完整样本

  

不要忘记粘贴解决方案代码

import Foundation

extension Action: CustomStringConvertible {
    var description: String {
        var result = "Action - "
        switch state {
            case .state(let value): result += "State.\(value)"
            case .cancelled: result += "cancelled"
        }
        return result
    }
}

let obj = Action()
print(obj)
obj.set(state: .failed)
print(obj)
obj.set(state: .succeeded)
print(obj)
obj.cancel()
print(obj)

结果

//Action - State.started
//Action - State.failed
//Action - State.succeeded
//Action - cancelled