Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Created November 23, 2021 08:29
Show Gist options
  • Save brownsoo/6a665e9fbe7fa9296b7c2b764aabfc2a to your computer and use it in GitHub Desktop.
Save brownsoo/6a665e9fbe7fa9296b7c2b764aabfc2a to your computer and use it in GitHub Desktop.
extension for KVO
extension NSObjectProtocol where Self: NSObject {
func observe<Value>(_ keyPath: KeyPath<Self, Value>,
onChange: @escaping (Value?) -> Void) -> NSKeyValueObservation {
return observe(keyPath, options: [.initial, .new]) { _, change in
onChange(change.newValue)
}
}
func bind<Value, Target>(_ sourceKeyPath: KeyPath<Self, Value>,
to target: Target,
at targetKeyPath: ReferenceWritableKeyPath<Target, Value>) -> NSKeyValueObservation {
return observe(sourceKeyPath) { (value) in
guard let newValue = value else { return }
target[keyPath: targetKeyPath] = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment