21. Property Observers in Swift

Swift provides a very nice feature to observe properties of a class. When ever the value of the variables updates, this new feature will update you that what did you change. Lets take a class called Person with two properties name and age.

class Person { 
     // properties 
     var name : String = "Khan" 
     var age : Int = 10 
}

Now lets implement property observer with each property to keep track of values.

var name : String = "Khan"{
       willSet{
           println("New value will be \(newValue)")
       }
       didSet{
            println("Old value was \(oldValue)")
       }
}

willSet and didSet are these two observers which will keep track of new and old values. willSet is called just before the value is stored and didSet is called after the new value is stored. These two observers are not dependent on each other, you can choose both or any of them according to your requirements.

var person = Person()
person.name = "Jhon"

Create a person object and assign new value “Jhon” to name property. Open Assistant Editor (VIEW -> Assistant Editor ->Show Assistant Editor) and observe these changes.

newValue and oldValue are two parameters which are provided by Swift. If you do not like these parameter names, you can change them easly.

var age  : Int = 10{
    willSet (newAge){ 
         println("New value will be \(newAge)")
    }
    didSet (oldAge){
         println("Old value was \(oldAge)")
    }
}

 

Continue with class and lazy property…..

 

 

Download file from GitHub