我想分享一些枚举属性。就像是:
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
State
cancelled
我知道如何获得上述逻辑来复制案例ActionState并在set函数中进行切换。但我正在寻找更好的方法。
set
我知道枚举不能在Swift中继承,并且我已经阅读了swift-enum- inheritance的协议答案。它没有解决“继承”或包括来自另一个枚举的案例的需要,仅解决了属性和变量。
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