加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:25:13 所属栏目:百科 来源:网络整理
导读:我想分享一些枚举属性.就像是: 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
我想分享一些枚举属性.就像是:
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继承(因为被取消的状态在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)

结果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读