Search code examples
swiftvariablessaveglobalexit

How do you save a global variable in swift once app has closed?


I have created a global variable in "view controller 1" which appears properly across my 3 different view controllers. I am incrementing this global variable in "view controller 2" and presenting the result also in "view controller 3". This is all functioning properly.

My issue is that when I close the app, my global variable resets to the originally assigned value. This is some of the code in "view controller 1":

var globalScore = 1

import UIKit

class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
}

And this some code in "view controller 2":

UserDefaults.standard.set(globalScore, forKey: "savedLevel")

Can someone please give a basic example of how to save global variables even once app is closed?

Thanks


Solution

  • Do

    var globalScore:Int { 
        get {
            return UserDefaults.standard.integer(forKey:"savedLevel")
        }
        set {
         UserDefaults.standard.set(newValue, forKey: "savedLevel")
       }
     }