標籤:swift計算屬性
一、計算屬性的概念
計算屬性本身不儲存資料,而是從其它儲存屬性中計算得到資料,與儲存屬性不同,類、結構體、和枚舉都可以定義計算屬性
計算屬性提供了一個getter來擷取值,以及一個可選的setter來間接設定其它屬性或變數的值,計算屬性的文法如下:
物件導向類型 類型名{
儲存屬性...
var 計算屬性名稱:屬性資料類型{
get {
return 計算後屬性值
}
set 新屬性值{
}
}
樣本:
class Employee { var no:Int = 0 var firstName:String = "" var lastName:String = "" var job:String? var salary:Double = 0 lazy var dept:Department = Department() var fullname:String{ get{ return firstName+"."+"lastName"} set(newFullName)系統預設給的變數名為newvalue{ var name = newFullName.componentsSeperatedByString(".") firstName = name[0] lastName = name[1]}}}
二、唯讀計算屬性
計算屬性可以只有getter訪問器,沒有setter訪問器,這就是唯讀計算屬性
樣本:
class Employee { var no:Int = 0 var firstName:String = "" var lastName:String = "" var job:String? var salary:Double = 0 lazy var dept:Department = Department() var fullname:String{ get{ return firstName+"."+"lastName"} }}
三、結構體和枚舉中的計算屬性
樣本
struct Department {
let no:Int = 0
var name : String = "sales"
var fullName:String {
return "swift" + name + ".D"
}
}
var dept = Department()
println(dept.fullName)
enum WeekDays:String {
case Monday = "Mon"
case Tuesday = "Tue"
case Wednesday = "Wed"
case Thursday = "Thu"
case Friday = "Fri"
var message:String {
return "Today is"+self.rawValue
}
}
var day = WeekDays.Monday
println(day.message)
本文出自 “平凡之路” 部落格,請務必保留此出處http://linjohn.blog.51cto.com/1026193/1621924
Swift計算屬性