我想分享一些枚举属性.就像是:
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 } }@H_404_3@我明白为什么ActionState不能从State继承(因为被取消的状态在State中没有表示)但我仍然想说“ActionState就像有更多选项的State,而ActionState可以获得State类型的输入,因为它们也属于ActionState类型“ @H_404_3@我看到如何使用上述逻辑来处理在ActionState中复制案例并在set函数中进行切换.但我正在寻找更好的方法. @H_404_3@我知道枚举不能在Swift中继承,我已经阅读了swift-enum-inheritance的协议答案.它没有解决“继承”或包含来自另一个枚举的案例的需要,而只涉及属性和变量.
固定代码
原文链接:https://www.f2er.com/swift/319125.htmlimport Foundation enum State { case started case succeeded case Failed } enum ActionState { case state(value: State) case cancelled } class Action { var state: ActionState = .state(value: .started) func set(state: State) { self.state = .state(value: state) } func cancel() { self.state = .cancelled } var description:String { var result = "Action " switch state { case .state(value: .started): result += "\(state)" case .state(value: _): result += "\(state)" case .cancelled: result += "cancelled" } return result } } let obj = Action() print(obj.description) obj.set(state: .Failed) print(obj.description) obj.set(state: .succeeded) print(obj.description) obj.cancel() print(obj.description)@H_404_3@结果 @H_404_3@