Search code examples
iosswiftuiviewcontrolleraccess-control

Proper way to retain value in a ViewController for when it re-appears


I have two ViewControllers: MainVC and SettingsVC. MainVCs behavior depends on a value that is set at runtime in SettingsVC. When segueing from SettingsVC to MainVC, I hand over the value via prepareForSegue(). No Problem!

But when loading the SettingsVC again to set the value again what is the best way to have it remember the last value it had?

Is there maybe a way to create a global variable, that can be accessed by both MainVC and SettingsVC?


Solution

  • Yes you can use let outside of a class to make that variable global. Say if you have this code in your MainVC

    import UIKit
    
    var param = 1
    class MainVC: UIViewController {
        ...
    }
    

    Then this variable param is visible in your settingVC.

    However, a better practice will be passing the variable through segue. When you segue to your SettingVC, simply pass the setting value back from your MainVC by prepareForSegue(). If you want to pass value when segue back, you are looking for an unwind segue. Here is a tutorial for that.