![](/img/trans.png)
[英]Is it possible to allow didSet to be called during initialization in Swift?
[英]swift didSet not called in a singleton
讓我們說我有一個單身經理
class Manager {
static let sharedInstance = Manager()
var text: String {
didSet (value) { print("didSet \(value)") }
}
init () {
self.text = "hello"
}
}
如果我做
Manager.sharedInstance.text = "world"
文字仍然是'你好',但如果我做了兩次,第二次是世界
它工作正常。
您經歷的行為由2個事實解釋
正如Apple 所說 ,在init
期間沒有調用didSet
(和willSet
)。
willSet和didSet觀察者提供了一種在設置變量或屬性的值時觀察(並適當響應)的方法。 首次初始化變量或屬性時,不會調用觀察者。 相反,只有在初始化上下文之外設置值時才會調用它們。
didSet
的參數確實引用了舊值 ,所以你應該這樣做
value
重命名為oldValue
。 print
使用text
所以從此
didSet (value) { print("didSet \(value)") }
對此
didSet (oldValue) { print("didSet \(text)") }
而是在您的代碼中打印舊值(已被覆蓋的值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.