Created
November 23, 2021 08:29
-
-
Save brownsoo/6a665e9fbe7fa9296b7c2b764aabfc2a to your computer and use it in GitHub Desktop.
extension for KVO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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