Swift Technocrat
Swift Technocrat

Reputation: 33

How is didSet and willSet implemented in Swift

I am trying to understand the implementation of willSet and didSet in Swift. I would like to know if there is anyway, under the hood, swift relies on Obj-C KVO mechanism when a var is declared as follows. Note: This is used in a Cocoa app. I have to declare the var as @objc dynamic so as to bind this var to a control on UI.

@objc dynamic var someString: String? = nil {
        didSet {
            self.doSomething()
        }
    }

Upvotes: 2

Views: 372

Answers (2)

Sam Furlong
Sam Furlong

Reputation: 106

No, they do not rely on KVO. To prove it let's look at the code that didSet and willSet are syntactic sugar for

var x = 0;

func setX(newX:Int):Int {
   willSet()
   x = newX
   didSet()
}

Instead of needing to write all the above boilerplate for that Swift just generates something similar under the hood. If it helps think of = as simply a set function on whatever is on the left had side of the equals. If I call = on a property it is simply calling set function on that property. Under the hood when I call = on a property Swift will call the didSet and willSet as in above. The exact implementation may look a little different but the above snippet should at least convince you that it would be unnecessary to implement property observers with KVO, and that if you dug deep within the source code for swift you would find that that didSet and willSet and computed properties themselves are merely syntactic sugar for the above code.

Upvotes: 1

vadian
vadian

Reputation: 285069

willSet/didSet and @objc dynamic are two different things.

  • willSet/didSet are lightweight Property Observers which are independent of KVO.
  • @objc dynamic exposes the property to Objective-C KVO. It's required for Cocoa Bindings

Upvotes: 2

Related Questions