原創(chuàng)文章戚炫,歡迎轉(zhuǎn)載。轉(zhuǎn)載請注明:關(guān)東升的博客
計算屬性本身不存儲數(shù)據(jù)媳纬,而是從其他存儲屬性中計算得到數(shù)據(jù)双肤。
計算屬性概念:
計算屬性提供了一個getter(取值訪問器)來獲取值施掏,以及一個可選的setter(設(shè)置訪問器)來間接設(shè)置其他屬性或變量的值。計算屬性的語法格式如下:
面向?qū)ο箢愋?類型名 {
存儲屬性
......
var 計算屬性名: 屬性數(shù)據(jù)類型 {
get {
return 計算后屬性值
}
set (新屬性值) {
......
}
}
}
定義計算屬性比較麻煩茅糜,要注意后面的幾個大括號的對齊關(guān)系七芭。
我們先看一個示例:
import Foundation
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 { //計算屬性
get {
return firstName + "." + lastName //返回拼接的結(jié)果
}
set (newFullName) { //存儲傳遞進(jìn)來的參數(shù)值
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) //取出屬性值
emp.fullName = "Tom.Guan" //給屬性賦值
print(emp.fullName)
只讀計算屬性:
計算屬性可以只有g(shù)etter訪問器,沒有setter訪問器蔑赘,這就是只讀計算屬性狸驳。指定計算屬性不僅不用寫setter訪問器,而且get{}代碼也可以省略缩赛。與上一節(jié)相比耙箍,代碼將大大減少。修改上一節(jié)示例為只讀計算屬性,代碼如下:
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 { //簡潔的setter訪問器
return firstName + "." + lastName
}
}
struct Department {
let no: Int = 0
var name: String = ""
}
var emp = Employee()
print(emp.fullName)
只讀計算屬性不能夠賦值,下列語句是錯誤的蛋济。
emp.fullName = "Tom.Guan"