Property observers

Property observers are called every time the value of the property is set. We can add property observers to any non-lazy stored property. We can also add property observers to any inherited stored or computed property by overriding the property in the subclass. We will look at the Overriding properties section a little later in this chapter.

There are two property observers that we can set in Swift: willSet and didSet. The willSet observer is called right before the property is set, and the didSet observer is called right after the property is set.

One thing to note about property observers is that they are not called when the value is set during initialization. Let's look at how we can add a property observer to the salary property of our EmployeeClass class and EmployeeStruct structure:

var salaryYear: Double = 0.0 {  
  willSet(newSalary) { 
    print("About to set salaryYear to (newSalary)") 
  } 
  didSet { 
    if salaryWeek>oldValue {  
      print("(firstName) got a raise.") 
    }else { 
      print("(firstName) did not get a raise.") 
    } 
  } 
} 

When we add a property observer to a stored property, we need to include the type of the value being stored within the definition of the property. In the preceding example, we did not need to define our salaryYear property as a Double type, however, when we add property observers, the definition is required.

After the property definition, we define the willSet observer that simply prints out the new value that the salaryYear property will be set to. We also define a didSet observer that will check whether the new value is greater than the old value, and if so, it will print out that the employee got a raise; otherwise, it will print out that the employee did not get a raise.

As with the getter method with computed properties, we do not need to define the name for the new value of the willSet observer. If we do not define a name, the new value is put in a constant named newValue. The following example shows how we can rewrite the previous willSet observer without defining a name for the new value:

willSet { 
  print("About to set salaryYear to (newValue)") 
} 

As we have seen, properties are mainly used to store information associated with a class or structure. Methods are mainly used to add the business logic to a class or structure. Let's look at how we add methods to a class or structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset