Search code examples
iosswiftxcodeuikitnsuserdefaults

Using UserDefaults to store score for a clicker game (Swift 5)


Have made a simple incremental game. I want it so that even if I go to a different VC and then return to the game, or reopen the game, it will show the current score. My issue is that if I leave the game, then the score will return back to zero. I do not want that to happen. The score should not be resetting. I've heard I could use UserDefaults but I am not familiar to it at all. If you can explain using code, that would be best. Thanks.

import UIKit

class CookieClickerVC: UIViewController {

@IBOutlet weak var goldLabel: UILabel!
@IBOutlet weak var numberOfGold: UILabel!
@IBOutlet weak var getGoldButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    formatItems()
    let defaults = UserDefaults.standard
    defaults.set(0, forKey: "goldCount")

}



@IBAction func getGoldClicked(_ sender: Any) {
    goldCount += 1
    numberOfGold.text = ("\(goldCount)")
}`

also, you may have already figured out, but goldCount is an unresolved identifier. How should I change the code after button is clicked?


Solution

  • Step 1: declare your goldCount variable and set the initial value to 0

    Step 2: on viewDidLoad, get the value stored in the UserDefaults and set it to goldCount

    Step 3: Also update your label

    Step 4: Update the value of goldCount in userDefaults

    import UIKit
    
    class CookieClickerVC: UIViewController {
    
        @IBOutlet weak var goldLabel: UILabel!
        @IBOutlet weak var numberOfGold: UILabel!
        @IBOutlet weak var getGoldButton: UIButton!
    
        //Step1: declare your goldCount variable and set initial value to 0
        var goldCount = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
            formatItems()
            //Step2: on viewDidLoad, get the value stored in the UserDefaults and set it to goldCount
            goldCount = UserDefaults.standard.integer(forKey: "goldCount")
            //Step3: then also update your label
            numberOfGold.text = ("\(goldCount)")
    
    
        }
    
        @IBAction func getGoldClicked(_ sender: Any) {
            goldCount += 1
            numberOfGold.text = ("\(goldCount)")
            //Step4: update the value of goldCount in userDefaults
            UserDefaults.standard.set(goldCount, forKey: "goldCount")
        }
    }