Swift how to tell when a variable changed in a shared instance

I would create a didSet value observer on that variable. Then when any ViewController willappear, set the delegate to self. And track the changes of that variable on the ViewController.

Each ViewController should do:

class ViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        Singleton.shared.delegate = self
    }
}

extension ViewController: SingletonDelegate {
    func variableDidChange(newVariableValue value: Int) {
    //here u get value if changed
    }
}

And the Singleton with your variable and protocol

protocol SingletonDelegate: class {
    func variableDidChange(newVariableValue value: Int)
}

class Singleton {

    var variable:Int = 0 {
       didSet {
          delegate?.variableDidChange(newVariableValue: variable)
       }
    }

    private init() {}
    weak var delegate: SingletonDelegate?

    static let shared = Singleton()
}

PD: notice this way only the top ViewController in the navigation will handle the newValue event.


I have used this pattern a few times and I prefer to use NotificationCenter.

In your Singleton class you need to use Post method every time the value changes , And in your viewcontroller you would add the observer to reflect or react to the change.

There are multiple ways to tackle this. And there are plenty of great tutorials out there for the same.

Tags:

Swift