In order to listen to changes in properties, Swift provides attribute observers, which can listen to changes in storage properties, even if they are different before and after the change, but they can not delay changes in storage properties and constant storage properties
There are two main attributes observed in Swift in the following ways:
1. Willset: The observer is called before the modification;
2. Didset: The observer is called after the modification;
The syntax for a property observer is as follows:
Object-oriented type type name {
var Store property: Property Data type = initial value {
Willset (new value) {
}
Didset (old value) {
}
}
}
Example
Class employee{
var no:int = 0
var name:string {
Willset (Newnamevalue) {
println ("New value for Employee name: \ (newnamevalue)")
}
Didset (Oldnamevalue) {
println ("Employee name's old value: \ (oldnamevalue)")
}
}
var job:string?
var salary:double=0
var depet:department?
}
struct Department {
var no:int = 10 {
willset{
println ("New value for department number: \ (newvalue))")
}
}
didset{
println ("department number old value \ (oldValue)")
}
}
This article is from the "Ordinary Road" blog, please be sure to keep this source http://linjohn.blog.51cto.com/1026193/1622088
SWIFT attribute Observer