Demo
struct SQIStruct {
var property_000: Int?
var property_002: Int?
}
class SQIClass {
var structProperty: SQIStruct = SQIStruct() {
didSet {
print("SQIClass's structProperty didSet~")
}
}
}
/// didSet 会被调用么 ? => Yes
SQIClass().structProperty.property_002 = 2
Why ?
为什么
属性观察器
会响应 struct 属性的变化 ? 因为 struct 是值类型
;
Apple官方对 Property Observers 的解释:
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
更详细的说明, 来自 stack overflow:
Property observers of value types (e.g. structures) are called also when an underlying property of the type instance is set; simply since the value of the instance itself is updated. The same does not hold for reference types; as long as the reference itself is not mutated, the property observer will not be called (i.e., the reference itself can be considered the value of reference types).1
思考
当 struct 中的某个属性被赋值, 会生成一个新的 struct 来替换旧的 struct, 新的 struct 包含新的属性 ?