Engineering

Creating Box that can observe updating value

We can observe the changed value of a variable. Just like this.

var name: String {
  didSet {
    // here
  }
}

DidSet is very helpful. For example, printing about changing value for debugging.
But, If you have so many variables? You may be tired typing.

So, We can use KeyPath in Swift4.
KeyPath can read or write some value.

In my approach, Wrapped by Box, then updating from KeyPath.
So, updating operations pass the same function every time.
We can add any operations in the function.

Create Box

class Box<T> {

  private var _value: T {
    get { return value }
    set { value = newValue }
  }

  private var value: T

  init(_ value: T) {
    self.value = value
  }

  func update<E>(_ value: E, _ keyPath: WritableKeyPath<T, E>) {
    let old = _value[keyPath: keyPath]
    _value[keyPath: keyPath] = value
    print("Did change value \(old) -> \(value)")
  }
}

Usage

One of the usages is below.

class State {
  var a: String = "a"
  var b: String = "b"
}

let box = Box(State())

box.update("abc", \.a)
Did change value a -> abc