In this tutorial we will set property observers for our properties by setting property observers we can observe the states of our properties. Property observers can be set using two keywords "willSet && didSet". We can use these two keywords in the property declaration && then will assign actions that will execute when value of property is about to change and when the value of property just changed. Consider an example of Library in which when a book added then the amount of books will change by number of books added.
class Library {
var numberOfBooks: Int = 100
var nameOfLibrary: String = "Oxford"
willSet {
println("numberOfBooks in Library are about to change to \(newValue)")
}
didSet {
println("numberOfBooks in Library just changed to \(self.numberOfBooks)")
}
func addBooks() -> String {
return "number of books in the \(self.nameOfLibrary) library are now \(self.numberOfBooks)"
}
}
Now make an object of the Library class && then change the value of the numberOfBooks to any value:
l1 = Library()
l1.numberOfBooks = 200
After doing this you will get two notifications printed on the console:
a.)numberOfBooks in Library are about to change to 200
b.)number of books in the Oxford library are now 200.
class Library {
var numberOfBooks: Int = 100
var nameOfLibrary: String = "Oxford"
willSet {
println("numberOfBooks in Library are about to change to \(newValue)")
}
didSet {
println("numberOfBooks in Library just changed to \(self.numberOfBooks)")
}
func addBooks() -> String {
return "number of books in the \(self.nameOfLibrary) library are now \(self.numberOfBooks)"
}
}
Now make an object of the Library class && then change the value of the numberOfBooks to any value:
l1 = Library()
l1.numberOfBooks = 200
After doing this you will get two notifications printed on the console:
a.)numberOfBooks in Library are about to change to 200
b.)number of books in the Oxford library are now 200.