我有一个问题,当变量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 或任何其他方法来完成此操作吗?如果是这样,请告诉我该怎么做。
提前谢谢您。
您可能只想从当前状态导出当前操作,而不是保存两者并尝试使它们保持同步:
class Entity {
var atState: CurrentState
var inAction: CurrentAction {
switch atState {
case .performAction(let action): return action
default: return .none
}
}
}