original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
to listen for changes in the properties, Swift provides a property observer. Property observers can listen for changes in storage properties, even if the values are the same before and after the change.
- Willset : The observer was called before the modification.
- Didset : The Observer is called immediately after the modification.
The syntax format for a property observer is as follows:
Object - oriented type type name {... var store property: Attribute Data type = initialization value { Willset (new value) { //Definition Willset observer. The "new value" is a parameter passed to the Willset Observer, which holds the new value that will replace the original property ... } Didset (old value) { //Definition Didset observer. The old value is the argument passed to the Didset Observer, which holds the old value replaced by the new attribute. ... } }
The syntax format of the attribute observer is more chaotic than the computed attribute.
Attribute observers can be used in classes and structs, and cannot be used in enumerations.
The sample code is as follows:
class Employee {var no:int = 0 var name:string = "Tony" {Willset (Newnameval UE) {//Willset observer for the Name property, Newnamevalue is the parameter name that we assigned to pass the new value print ("Employee name new value: \ (Newnamevalue)")} Didset (Oldna Mevalue) {//Didset Observer that defines the Name property, Oldnamevalue is the parameter name that we assigned to pass the old value print ("Employee name old value: \ (Oldnamevalue)")}} var Job:string? var salary:double = 0 var dept:department?} struct Department {var no:int = ten {willset {////Willset observers that define no property, note that there are no declared arguments here, but we can Internal Use newvalue Print ("Department number new value: \ (NewValue)")} didset {//Didset Observer that defines the No property, note that there is no parameter declared here, but we can use OL in the viewer Dvalue Print ("department number old value: \ (oldValue)")? }} var = "name:string"} var emp = Employee () emp.no = 100emp.name = "Smith"? var dept = Department () dept.no =?
The result of the above code operation is as follows:
Employee Name new value: Smith Employee name Old value: Tony department number new value: 30 department number old value: 10
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
?
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
2008Swift 2.0 Study notes (Day 33)--Attribute Viewer