I would like to know when a set of properties of a Swift object changes. Previously, I had implemented this in Objective-C, but I\'m having some difficulty converting it to
My original 'second attempt' contains a bug that will fail to detect when a value changes to or from nil. The first attempt can actually be fixed once one realizes that all values of 'change' are NSObject:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let oldValue: NSObject? = change?[.oldKey] as? NSObject
let newValue: NSObject? = change?[.newKey] as? NSObject
if newValue != oldValue {
edit()
}
}
or a more concise version if you prefer:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if change?[.newKey] as? NSObject != change?[.oldKey] as? NSObject {
edit()
}
}