計算屬性本身不存儲數據,而是從其他存儲屬性中計算得到數據。
計算屬性概念:
計算屬性提供了一個getter(取值訪問器)來獲取值,以及一個可選的setter(設置訪問器)來間接設置其他屬性或變量的值。計算屬性的語法格式如下:
面向對象類型類型名 {
存儲屬性
......
var 計算屬性名: 屬性數據類型 {
get {
return 計算後屬性值
}
set (新屬性值) {
......
}
}
}
定義計算屬性比較麻煩,要注意後面的幾個大括號的對齊關系。
我們先看一個示例:
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 //返回拼接的結果
}
set (newFullName) { //存儲傳遞進來的參數值
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)
只讀計算屬性:
計算屬性可以只有getter訪問器,沒有setter訪問器,這就是只讀計算屬性。指定計算屬性不僅不用寫setter訪問器,而且get{}代碼也可以省略。與上一節相比,代碼將大大減少。修改上一節示例為只讀計算屬性,代碼如下:
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)
只讀計算屬性不能夠賦值,下列語句是錯誤的。
1
emp.fullName = "Tom.Guan"