Explain willSet and didSet property observers in Swift?

We can use either one or both of the following property observers to observe and respond to property changes.

  • willSet is called just before the value is changed.
  • didSet is called immediately after the new value is set.

If we implement the willSet property observer, it is passed with the new value as a constant parameter. We can either provide a parameter name or else a default name of newValue  will be used. The parameter name is provided within parentheses.

if we implement the didSet property observer, it is passed with the old value as a constant parameter. We can either provide a parameter name or else a default name of oldValue will be used.

More about property observers in Swift…

Example code using willSet, didSet property observer…

Leave a Reply