As mentioned before, KVO leverages Objective-C's dynamism, which means it doesn't work on structs.
In order to use KVO with your own Swift objects, you have to make them dynamic and compatible with Objective-C using the @objc annotation:
class MyObject: NSObject {
@objc dynamic
var string: String = ""
}
Now, the string member is observable, and you can use the following code:
let object = MyObject()
var changed = false
let observer = object.observe(\MyObject.string) { (obj, change) in
// Do Something with the new value
changed = true
}
object.string = "This will emit an event"
assert(changed) // ensure changed was called
observer.invalidate() // Always invalidate!
With this technique, it is possible to listen to multiple changesĀ from different call sites and multiple objects. This method is not the most practical in Swift, but still lets you interface properly with Objective-C code and APIs such as Foundation, UIKit, AppKit, and more.
Also, some objects such as AVPlayerItem in AVFoundation are designed to leverage KVO. To keep track of changes in status, or to know when duration has been computed, you'll need to observe for the appropriate properties.