The property observer mechanism allows the program to gain the opportunity to run code when the property is assigned, to monitor property value changes other than the initialization of the property, and to respond to the value of the property when it has changed
Contains two special callback methods in detail:
Willset (NewValue): The property being observed is about to be assigned the method itself before it is called.
Didset (Old Value): The observed property is assigned to the method itself when it is evaluated.
Scope of observation
All storage properties except deferred storage properties (containing instance store properties or type store properties).
Inherited properties (containing storage properties and computed properties) can be overloaded by adding
attribute observer-defined syntax format
[修饰符] var 存储属性名:属性类型[=初始值]{ willSet(newValue){//属性即将被赋值之前自己主动运行的代码}didSet(oldValue){//属性被赋值完毕之后自己主动运行的代码}}
Description
The Willset:willset section defines a run-time code in which the observed property is to be actively run before it is assigned a value.
The Willset section is able to explicitly develop a formal name that represents the new value that the property will be set to. Swift can also omit this formal name. Swift will provide an implicit formal name for the form: NewValue.
The Didset:didset section defines a running code that is actively run by the observed property after it has been successfully assigned. The Didset section is able to explicitly develop a formal name that represents the old value before the property will be altered. Swift is also able to omit this name, and Swift will provide an implicit formal name for the form: OldValue.
class Person { var age:Int=0 { willSet{ if(newValue<0 || newValue>200) { print("你输入的有误。非人类呀") } else{ print("即将成功") } } didSet{ print("已完毕,原来的年龄为\(oldValue)") } }} var p=Person() p.age=1000
Object-c---> Swift's (11) attribute Observer