## PROPERTIES
結構體和類(統稱為 types)可以擁有自己的變量和常量(統稱為 properties)。types 也可擁有方法來處理 properties:
~~~
struct Person {
var clothes: String
var shoes: String
func describe() {
print("I like wearing \(clothes) with \(shoes)")
}
}
let taylor = Person(clothes: "T-shirts", shoes: "sneakers")
let other = Person(clothes: "short skirts", shoes: "high heels")
taylor.describe() //"I like wearing T-shirts with sneakers"
other.describe() //"I like wearing short skirts with high heels"
//調用方法時,不同的對象使用相應的值
~~~
### Property observers
Swift 提供了兩個觀察者方法,willSet 和 didSet,分別會在屬性的值將要改變以及改變后觸發(常用于用戶界面的更新):
~~~
struct Person {
var clothes: String {
willSet {
updateUI("I'm changing from \(clothes) to \(newValue)")
}
didSet {
updateUI("I just changed from \(oldValue) to \(clothes)")
}
}
}
func updateUI(msg: String) {
print(msg)
}
var taylor = Person(clothes: "T-shirts")
taylor.clothes = "short skirts" //值改變,將會調用觀察者方法
~~~
### Computed properties
Computed properties 其實就是自己重寫屬性的 get/set 方法:
~~~
struct Person {
var age: Int
var ageInDogYears: Int {
get {
return age * 7
}
}
}
var fan = Person(age: 25)
print(fan.ageInDogYears) //輸出:25 * 7
~~~
### Static properties and methods
靜態屬性和方法屬于 type(class\struct),而不屬于類的實例,這可以更好的組織一個共享的儲存數據。通過 static 關鍵字聲明一個靜態變量:
~~~
struct TaylorFan {
static var favoriteSong = "Shake it Off"
var name: String
var age: Int
}
let fan = TaylorFan(name: "James", age: 25)
print(TaylorFan.favoriteSong)
//每個 TaylorFan 類型的對象都會有自己的名字和年齡,但他們都有共同喜歡的歌曲:"Shake it Off"
~~~
因為靜態屬性和方法存在于 類 中,所以靜態方法是無法訪問非靜態屬性的。