Swift 4 KVO API Not Observing

Hi,

The WWDC 2017 Whats New in Foundation says this functionality is coming soon. However XCode 9 has full complier support for this new syntax. I am trying to understand if this should work, or is not yet released?


Any thoughts on why the followinig does not work?


@objcMembers class Thing : NSObject {

dynamic var stuff : String = ""

}

let thing = Thing()

let observation = thing.observe(\Thing.stuff) { (model, change) in

// This closure never gets called!

}

thing.stuff = "New Stuff"

thing.stuff = "More New Stuff"


Do I need to write via keyPath values (i.e. thing[keyPath: \.stuff] = "New Stuff" ) ?


Thanks,


Andrew

I put exactly this code into a playground (Xcode 9), except that I added a print to the closure:


import Foundation

@objcMembers class Thing : NSObject {
  dynamic var stuff : String = ""
}

let thing = Thing()
let observation = thing.observe(\Thing.stuff) { (model, change) in
  print ("is called")
}

thing.stuff = "New Stuff"
thing.stuff = "More New Stuff"


The output was:


is called

is called


as expected. Note that if this is not your actual code, you must be careful to keep the observation (returned from thing.observe) around for as long as you want notifications. If "observation" is a variable in some local scope, it will deallocate and remove the observation as soon as you exit the scope.

Swift 4 KVO API Not Observing
 
 
Q