PROPERTIES

最后更新于:2022-04-01 04:44:36

## 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" ~~~ 因为静态属性和方法存在于 类 中,所以静态方法是无法访问非静态属性的。
';