Hacker News new | ask | show | jobs
by hyberbole_1234 1957 days ago
The best approach I’ve seen is separating State and Views and having some form of property diffing.

  struct LightState {
    var isLightOn: Bool
  }
  
  class LightViewController {
  
    let lightView = UIView()
  }
  
  class StateDirector<
    LightState,
    LightViewController> {
    
    let lightState: LightState
    
    init(state: LightState) {
      self.lightState = state
    }

    func bind(
      view: LightViewController
    ) { 
    
      // Every time is turned on changed call this
      LightState.add(
        listener: self,
        for keyPath: \.isTurnedOn,
        handle: .method(Self.handleLightChange)
    }

    func handleLightChange(isOn: Bool) {
    
      view.lightView.backgroundColor = isOn ?
        .green : .red
    }
  }
This allows clear separation of State, View and Changes.

You can then just model your state in your reducer and “simulate your views” inside Unit tests