Original articles, welcome reprint. Reprint Please specify: Dongsheng's Blog
Calculated Properties instead of storing the data itself, the data is computed from other storage properties.
computed attribute concepts:
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 property is as follows:
Object-oriented type type name { Store Properties ...... var Computed Property name: property data type { get { return post-computed attribute values } set (New attribute value ) { ...... } } }
It is troublesome to define computed properties, note the alignment of the following braces.
Let's look at an example first:
import foundation class employee { var no: int = 0 var firstname: string = "Tony" //Storage Properties var lastName: String = "Guan" //Storage properties var job: String? var salary: Double = 0 lazy var dept: department = department () var fullname: string { //Calculation Properties get { return firstName + "." +lastname //back to stitching results } set (Newfullname) { //stores the parameter values passed in var name =newfullname.componentsseparatedbystRing (".") firstName = name[0] lastName = name[1] } }}struct Department { let no: Int = 0 var name: String = ""}var emp = employee () print ( Emp.fullname) //Remove the attribute value emp.fullname = "Tom.guan" / /Assign a value to a property print (Emp.fullname)
  
Read-only computed properties:
calculated properties can be onlyGetteraccessor, noSetteraccessor, which isread-only computed properties. Specify calculated properties not only without writingSetteraccessors, andget{}The 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:
class employee { var no: int = 0 var firstname: string = "Tony" var lastName: String = "Guan" var job: string? var salary: double = 0 lazy var dept: department = department () var fullName: string { //Simple setter Accessor return firstName + "." +lastName } }struct Department { let no: Int = 0 var name: String = ""}var emp = employee () print (emp.fullname)
read-only computed properties cannot be assigned, the following statements are 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 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
Swift 2.0 Study Notes (Day 32)--Calculate attributes