Search code examples
swiftgetter-setter

Swift automatically set value to variable A by setting variable B


I've a question on whether or not it is possible to automatically set value to variable A when variable B gets updated. I've 2 variables set up as following:

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
}

What I'm trying to achieve is that, whenever variable atState gets a value:

anEntity.atState = .performAction(.walk)

anEntity.inAction automatically sets to:

anEntity.inAction = .walk

And whenever variable atState gets a value other than .performAction then anEntity.inAction automatically sets to:

anEntity.inAction = .none

Can this be done by using Swift getter and setter or any other methods? If so, please show me how to do it.

Thank you in advance.


Solution

  • You'll probably want to just derive the current action from the current state, rather than saving both and trying to keep them in sync:

    class Entity {
      var atState: CurrentState
    
      var inAction: CurrentAction {
        switch atState {
        case .performAction(let action): return action
        default: return .none
        }
      }
    }
    

    Another idea would be to move this responsibilit yonto CurrentState itself, so that you can easily get the action for any state anywhere else you might need it in your code:

    extension CurrentState {
      var inAction: CurrentAction {
        switch self {
        case .performAction(let action): return action
        default: return .none
        }
      }
    }
    
    class Entity {
      var atState: CurrentState
      // No need to store the action directly anymore
    }
    

    So now you can just access it with e.g. entity.atState.action.