Swift - Custom Type Property Observers

Introduction

Consider the following code


class Point {
   var x = 0.0
   var y = 0.0
   let width = 2
}

You can access the properties by specifying the property name using the dot syntax:

var ptA = Point()
//assigning values to properties

ptA.x = 15.0
ptA.y = 50.0

To enforce a range of valid numbers for both x and y, use property observers to observe and respond to changes in the properties' values.

In Swift, you can use two property observers:

observers Description
willSetFired before a property value is stored
didSet Fired immediately after a value is stored

For example

Demo

class Point {
     var x: Double = 0.0 {
          willSet(newX) {/*from  ww  w. j  a  v a 2s  .  c  o  m*/
             print("Going to assign a value of \(newX) to x")
          }
          didSet {
              print("Value of x before assignment : \(oldValue)")
              print("Value of x after assignment : \(x)")
              if x>100 || x<(-100) {
                  x = oldValue
              }
         }
}

Here, the willSet block of code will be executed when you try to assign a value to the x property.

It will be fired before the value is assigned to x.

After the value is assigned, the didSet block of code will execute.

Here, if the assigned value is less than -100 or greater than 100, then the old value of the property is restored.

If you do not specify a name after the willSet keyword, you can still retrieve the new value using the newValue keyword.

You can also specify a name after the didSet keyword; if not, the old value of the property can be retrieved using the oldValue keyword.

Property observers apply only to stored properties.

For computed properties, you can use a setter to check the validity of a value before assigning it to a property.

Property observers are not called when a property is first initialized.

They will only be called when a property is modified outside of initialization.

Related Topic