简体   繁体   中英

swift didSet not called in a singleton

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

It is working fine.

The behaviour your experienced is explained by 2 facts

Fact 1

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.

Fact 2

The parameter of didSet does refer to the old value , so you should

  1. rename value as oldValue .
  2. use 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM