Swift - 属性观察器 Property Observer
2016-06-15 本文已影响1282人
小黑Swift
属性观察器可让我们在使用属性时候,在希望一个属性发生改变时候进行某些操作。也就是一些小的代码块,可在一个属性值即可发生改变之前 willSet 或者之后 didSet 运行。要创建一个属性观察器,可在属性后面添加大括号(类似对计算属性的做法)
class PropertyObserverExmple {
var number: Int = 0 {
willSet(newNumber) {
print("About to change to \(newNumber)")
}
didSet(oldNumber) {
print("Just changed from \(oldNumber) to \(self.number)")
}
}
}
var observer = PropertyObserverExmple()
observer.number = 4
// About to change to 4 ,Just changed from 0 to 4
使用例子-比如更换UI主题模式
//属性观察器 Property Observer
//注意:didSet 和 willSet 不会再初始化阶段init时候调用
enum Theme {
case DayMode
case NightMode
}
class UI{
private var fontColor: UIColor!
private var backgroundColor: UIColor!
var themeMode: Theme = .DayMode {
didSet {
self.changeTheme(themeMode)
}
}
init(themeMode: Theme) {
self.themeMode = themeMode
self.changeTheme(themeMode)
}
private func changeTheme(themeMode: Theme) {
switch themeMode {
case .DayMode:
fontColor = UIColor.blackColor()
backgroundColor = UIColor.whiteColor()
case .NightMode:
fontColor = UIColor.whiteColor()
backgroundColor = UIColor.blackColor()
}
}
}
themeMode