小编典典

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

swift

我想分享一些枚举属性。就像是:

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(因为状态cancelled在中没有表示形式State),但是我仍然想说“
ActionState就像具有更多选项的State,并且ActionState可以获取类型为State的输入,因为它们也属于输入ActionState”

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

我知道枚举不能在Swift中继承,并且我已经阅读了swift-enum-
inheritance的协议答案。它没有解决“继承”或包括来自另一个枚举的案例的需要,仅解决了属性和变量。


阅读 250

收藏
2020-07-07

共1个答案

小编典典

细节

  • 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
2020-07-07