我想分享一些枚举属性。类似的东西:
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
中没有任何代表),但我仍希望能够说&# 34; ActionState就像具有更多选项的State,ActionState可以获得State类型的输入,因为它们也是ActionState"
我知道如何使用上述逻辑来复制ActionState
中的案例并在set
函数中进行切换。但我正在寻找更好的方法。
我知道枚举无法在Swift中继承,我已经阅读了swift-enum-inheritance的协议答案。它没有解决继承"的问题。或者包括来自另一个枚举的案例,但只包括属性和变量。
答案 0 :(得分:13)
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