Here's an explanation from Apple that when setting a new value for a property, you can do some processing before and after setting it, and these two keywords are like monitoring the property changes.
If you don ' t need to compute the property but still need to provide code that's run before and after setting a new value, Use willSet
and didSet
. For example, the class below ensures and the side length of its triangle are always the same as the side length of its squ Is.
Code description
Class man:nsobject{
var Isyoung:bool
var name:string = "Anonymous"
{
willset{
println ("would set name to \ (name)")
}
didset{
println ("did set name from \ (oldValue) to \ (name)")
}
}
var age:int = 0{
willset{
println ("would set age to \ (age)")
}
didset{
println ("did set age from \ (oldValue) to \ (age)")
If age < 18{
Isyoung = True
}
else{
Isyoung = False
}
}
}
For an attribute variable that does not have an initial value set, it is initialized when it is created
Init (Isyong:bool) {
Self.isyoung = Isyong
Super.init ()
}
}
Let Gentleman:man = Mans (Isyong:false)
Gentleman.name = "Zhang San"
Gentleman.age = 17
Gentleman.isyoung
Output Result:
Would set name to anonymous
Did set name from anonymous to Zhang San
Would set age to 0
Did set age from 0 to 17
Swift keyword Willset and didset