Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value . Let's have a look at the code snippet below to help us have a better understanding of how property observers willSet and didSet works.
import UIKit
struct Person {
var name: String
var age: Int
}
class ViewController: UIViewController {
var person: Person? {
didSet{
print("Called after setting the new value")
if let name = person?.name {
print("New name is \(name) and old name is \(String(describing: oldValue?.name))")
}
}
willSet(myNewValue) {
print("Called before setting the new value")
if let newName = myNewValue?.name {
print("New name is \(newName)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
person = Person(name: "Shem", age: 4)
}
}
Property observers are declared as a variable and not as constants because it is only a mutable property that can be tracked by property observers. Hence, property observers are declared with var and not the let keyword.