枚举可以在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
  }
}@H_502_2@ 
 

我明白为什么ActionState不能从State继承(因为被取消的状态在State中没有表示)但我仍然想说“ActionState就像有更多选项的State,而ActionState可以获得State类型的输入,因为它们也属于ActionState类型“

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

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

固定代码
import 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_502_2@ 
 

结果

原文链接:https://www.f2er.com/swift/319125.html

猜你在找的Swift相关文章