Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Difference between KVO and willSet & didSet?

Tags:

ios

swift

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.

  1. Is there any difference between these two approaches?
  2. Does one have any advantage over the other?
like image 315
bibintomj Avatar asked Nov 16 '17 10:11

bibintomj


2 Answers

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.

like image 88
Leanid Vouk Avatar answered Nov 17 '22 00:11

Leanid Vouk


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.

like image 36
rob mayoff Avatar answered Nov 16 '22 23:11

rob mayoff