just wondering if this is possible in Swift 2.2, KVO on a computed property!?
ie:
var width = 0
var height = 0
private var area : Double {
get {
return with * height
}
}
self.addOberser(self, forKeyPath: "area", ......
Would a client code modifying the with or height trigger observeValueForKeyPath?
Just checking before engaging on a mayor class refactor. KVO's syntax being as annoying as it's is not worth even a playground if someone has an answer at hand (I am assuming answer is NO)
regards! ~d
That code won't work for two reasons:
You must add the
dynamic
attribute to thearea
property, as described in the section “Key-Value Observing” under “Adopting Cocoa Design Patterns” in Using Swift with Cocoa and Objective-C.You must declare that
area
depends onwidth
andheight
as described in “Registering Dependent Keys” in the Key-Value Observing Programming Guide. (This applies to Objective-C and Swift.) And for this to work, you also have to adddynamic
towidth
andheight
.(You could instead call
willChangeValueForKey
anddidChangeValueForKey
wheneverwidth
orheight
changes, but it's usually easier to just implementkeyPathsForValuesAffectingArea
.)Thus:
Output:
As @Rob stated in his answer, make
area
dynamic
to be observed from objective-cNow add
willSet { }
anddidSet { }
forwidth
andheight
properties,inside
willSet
for both properties add thisself.willChangeValueForKey("area")
and indidSet
addself.didChangeValueForKey("area");
Now observers of
area
will be notified every time width or height change.Note: this code is not tested, but I think it should do what expected