I have been working with willSet and didSet for a variable for a while. Its used to get notified and perform some action before and after a variable is changed.
I recently came across KVO which does similar thing, but with few more steps to setup.
KVO is Objective C approach to observe properties is based on dynamic dispatch
While didSet/willSet are pure Swift methods which doesn't exist in ObjC
The latter in theory should be more efficient since Swift is trying to use static dispatch where possible for performance gains.
I'd go with ObjC approach only if you need compatibility with some ObjC dependencies or legacy code.
KVO lets you implement the common “Observer” pattern. With KVO, you can attach any number of observers to a property, at run time, without modifying the source code of the property you're observing.
Swift's willSet
and didSet
“observers” are essentially functions that are called before and after a property is set, and have to be written into the property's source code at compile time. They serve a very different purpose than KVO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With