Swift 通过设置变量 B 来自动为变量 A 设置值

问题描述 投票:0回答:1

我有一个问题,当变量B更新时是否可以自动为变量A设置值。 我设置了 2 个变量如下:

enum CurrentState: Hashable {
    case uninitiated
    case idle
    case performAction(CurrentAction)
}

enum CurrentAction: Int {
    case eat
    case drink
    case walk
    case run
    case none
}

class Entity {
  var atState: CurrentState
  var inAction: CurrentAction
}

我想要实现的是,每当变量 atState 获得值时:

anEntity.atState = .performAction(.walk)

anEntity.inAction 自动设置为:

anEntity.inAction = .walk

每当变量 atState 获取 .performAction 以外的值时,anEntity.inAction 会自动设置为:

anEntity.inAction = .none

可以使用 Swift getter 和 setter 或任何其他方法来完成此操作吗?如果是这样,请告诉我该怎么做。

提前谢谢您。

swift getter-setter
1个回答
0
投票

您可能只想从当前状态导出当前操作,而不是保存两者并尝试使它们保持同步:

class Entity {
  var atState: CurrentState

  var inAction: CurrentAction {
    switch atState {
    case .performAction(let action): return action
    default: return .none
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.