[背景]
折腾:
期间,看了:
很明显:
此处感觉:
Computed properties
和:
Property Observers
怎么有点类似啊?
并且好像还有个Property
所以需要去搞清楚,Property,Computed properties和Property Observers的区别。
[折腾过程]
1.不过好像之前看的:
也解释了一点了:
get and set are for computed properties (they don’t have any backing store). (In my opinion, the keyword ‘var’ is confusing here)
- willSet and didSet are called for an instance variable (Use didSet to override any changes)
- set and get are purely for computed properties
2.搜:
swift Property vs Computed property vs Property Observer
参考:
[总结]
Property,是和一个类(结构体,枚举)相关的属性值
stored property,用来,为实例对象,存储,常量或变量的,值的
而computed property是用来,计算出一个值,(而不是存储一个值)
最佳例子,就是官网给的,一看就看懂了:
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}其中的center属性很明显是:
不是用于保存固定的常量值或变量值的,而是用于每次都动态的计算出最新的值的
所以叫做computed property
-》其实只是为了代码的调用者更加方便而已
-》如果你本身知道了此处的AlternativeRect的center的计算公式,其实完全可以去掉这个center属性,而每次都只是自己去用公式计算值就可以了。
center的存在,免去你的烦恼,方便你使用计算好的值,而已。
类,结构体,枚举,会有computed property
只有类和结构体,才会有stored property
stored property和computed property常常会和一个特性类型的实例有关系
而property也可以和类型本身有关系-》这类property被叫做type property
此外,你可以通过定义property observer去监控一个属性值的变化,由此可以响应自定义的动作。
property observer可以添加用于你自己定义的stored property,也可以用于继承了父类的子类的属性
而如何利用willSet和didSet去(重写overvide)stored property的值,官网给的例子:
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
stepCounter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
stepCounter.totalSteps = 896
// About to set totalSteps to 896
// Added 536 steps也基本说明问题了:
willSet:传入newXXX,然后加上你要处理的代码
didSet:在然后新的值设置完毕后,有啥还要后处理的,继续处理
get和set,是针对于计算值的Computed Properties的;
大概格式,还是直接参考官网代码吧:
struct someClassOrSturctOrEnum {
var value1 = initCode1
var value2 = initCode2
var computedProperty: SomeType {
get {
/* add compute code, to calculate some value out, such as:
calculatedValue = value1 +value2
……..
*/
return calculatedValue;
}
set {
/* add calculate code, such as:
value1 = newValue1
value2 = newValue2
……
*/
}
}
}property observer(的willSet和didSet)主要是针对于Stored Property的;
大概格式是:
class someClass{
var storedPropertyVar: ValueType = initValue {
willSet(newStoredPropertyVar) {
/* add process code */
}
didSet {
/* add extra process code */
}
}
} 即可。
转载请注明:在路上 » [已解决]Swift中Property、Computed property和Property Observer的区别