在 Swift 中,属性观察器(Property Observers)
在 Swift 中,属性观察器(Property Observers) 是一种可以监听和响应属性值变化的机制。通过属性观察器,你可以在属性的值被设置之前或之后执行特定的代码。属性观察器通常用于存储属性(Stored Properties),不能直接用于计算属性(Computed Properties),但可以通过其他方式间接实现类似功能。
属性观察器的类型
Swift 提供了两种类型的属性观察器:
willSet:
在属性的值被设置之前调用。
你可以通过一个默认参数(通常命名为 newValue)访问新值。
如果需要,可以自定义参数名称。
didSet:
在属性的值被设置之后调用。
你可以通过一个默认参数(通常命名为 oldValue)访问旧值。
如果需要,可以自定义参数名称。
属性观察器的使用规则
属性观察器只能添加到存储属性上,不能直接添加到计算属性上。
如果子类重写了父类的存储属性,并且该属性在父类中已经定义了观察器,那么子类可以添加额外的观察器或自定义行为。
如果属性的值在初始化时被设置(例如在初始化器中),willSet 和 didSet 不会被调用。
示例代码
1. 基本用法
swift
class Example {
var myProperty: Int = 0 {
willSet {
print("The value is about to change from \(myProperty) to \(newValue)")
展开全文}
didSet {
print("The value has changed from \(oldValue) to \(myProperty)")
}
}
}
let example = Example()
example.myProperty = 10
// 输出:
// The value is about to change from 0 to 10
// The value has changed from 0 to 10
2. 自定义参数名称
swift
class Example {
var myProperty: Int = 0 {
willSet(newVal) {
print("The value is about to change from \(myProperty) to \(newVal)")
}
didSet(oldVal) {
print("The value has changed from \(oldVal) to \(myProperty)")
}
}
}
let example = Example()
example.myProperty = 20
// 输出