1

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?

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! What I ended up doing was creating an action that pops up when you first enter the app, saying how many coins you earned offline. It covers up the label, so when you click the "OK" on the button it updates the amount of coins you have before it disappears. Thanks!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.