Reputation: 9870
Lets say I have a singleton Manager
class Manager {
static let sharedInstance = Manager()
var text: String {
didSet (value) { print("didSet \(value)") }
}
init () {
self.text = "hello"
}
}
If I do
Manager.sharedInstance.text = "world"
text is still 'hello' but if I do it twice, the second time it is world
Upvotes: 4
Views: 1216
Reputation: 59496
It is working fine.
The behaviour your experienced is explained by 2 facts
As Apple says didSet
(and willSet
as well) is not called during the init
.
The willSet and didSet observers provide a way to observe (and to respond appropriately) when the value of a variable or property is being set. The observers are not called when the variable or property is first initialized. Instead, they are called only when the value is set outside of an initialization context.
The parameter of didSet
does refer to the old value, so you should
value
as oldValue
.text
in the print
So from this
didSet (value) { print("didSet \(value)") }
to this
didSet (oldValue) { print("didSet \(text)") }
Instead in your code you are printing the old value (the one that has been overwritten).
Upvotes: 3