Original articles, welcome reprint. Reprint Please specify: Dongsheng's Blog
The computed property itself does not store the data, but instead computes it from other storage properties.
Calculate Attribute Concepts:
The computed property provides a getter (accessor) to get the value, and an optional setter (set accessor) to indirectly set the value of another property or variable. The syntax format for the computed attribute is as follows:
Object Type type name { Store property ... var Computed Property Name: property data type { get { return computed property value } set (new property value) {
...... } } }
It is troublesome to define computed properties, note the alignment of the following braces.
Let's look at an example first:
Import FoundationclassEmployee {varNo:int =0 varFirstname:string ="Tony" //Store Properties varLastname:string ="Guan" //Store Properties varJob:string?varSalary:double =0LazyvarDept:department =Department ()varfullname:string {//Calculated Properties Get { returnFirstName +"."+ LastName//returns the result of stitching } Set(Newfullname) {//Store the parameter values passed in varName = Newfullname.componentsseparatedbystring (".") FirstName= name[0] LastName= name[1] } }}structDepartment {Let no:int=0 varName:string =""}varEMP =Employee () print (emp.fullname)//Remove attribute valueEmp.fullname="Tom.guan" //Assigning a value to a propertyprint (emp.fullname)
read-only computed properties:
Computed properties can be only getter accessors, without setter accessors, which are read-only computed properties. Specifying a computed property not only does not have to write the setter accessor, but the get{} code can also be omitted. Compared to the previous section, the code is greatly reduced. Modify the previous section as a read-only computed property with the following code:
classEmployee {varNo:int =0 varFirstname:string ="Tony" varLastname:string ="Guan" varJob:string?varSalary:double =0LazyvarDept:department =Department ()varfullname:string {//Simple setter Accessor
}
struct Department {
Let No:int = 0
var name:string = ""
}
var emp = Employee ()
Print (Emp.fullname)
A read-only computed property cannot be assigned a value, and the following statement is incorrect.
Emp.fullname = "Tom.guan"
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 Products iOS, Cocos, mobile design courses please pay attention to the official website of Chi Jie Classroom: http://www.zhijieketang.com
Luxgen Classroom Forum Website: http://51work6.com/forum.php
Swift 2.0 Study Notes (Day 32)--Calculate attributes