Alec Norrie
Alec Norrie

Reputation: 113

Saving integer variable locally

This is my code for setting the defaults.

override func viewDidLoad() {

super.viewDidLoad()

let defaults = UserDefaults.standard
defaults.set("\(coins) $", forKey: "labelName") }

coins is my integer variable. It increases every time someone clicks a button.

labelName is my label that shows how many coins are earned.

How to make it so the number of coins are saved locally and then updated when someone restarts the app?

Upvotes: 1

Views: 66

Answers (2)

Donovan King
Donovan King

Reputation: 855

I wouldn't save coins as a string which is what you're doing here:

defaults.set("\(coins) $", forKey: "labelName")

Instead save it as an Integer:

// Set data (whenever you change the value)
var coins = 100
UserDefaults.standard.set(coins, forKey: "Money")

When you want to get the data back (in viewDidLoad perhaps):

// Get Data
coins = UserDefaults.standard.integer(forKey: "Money")

Upvotes: 1

Camden Lamons
Camden Lamons

Reputation: 26

I think you can save coins as an integer instead of a string, but then if you are using it as a string then you would have that change it back to a string after you accessed the data when you want to use it. If that makes sense.

Upvotes: 0

Related Questions