Naiem Salib Naiem Salib - 1 year ago 91
iOS Question

saving coins variable in swift 3

i am kinda new to swift and i need help with saving an int variable that holds the user's coins that they collect and saving it even after the app closes , so here is what i did , i have two scenes one represents startMenu which has the a struct that has the coins variable ( so i can easily control it from another scene ) , and the other scene which is GameScene , and in GameScene every time the user interacts with a coin node , it adds 1 to the coins variable in StarMenu Scene

here in my struct in StartMenu

struct Variables {

static var CoinsCollected = 0


and here is what i did to make it be saved

let defaults = UserDefaults.standard
defaults.set(Variables.CoinsCollected, forKey: "CoinsCollected")

and i have this line in GameScene inside my didbegin contact , when the user interacts with a coin

Variables.CoinsCollected += 1

and i have this line that updates the labelnode for the coins variable

coinsCollectedLabel = SKLabelNode(text: "coins: \(Variables.CoinsCollected)")

and everything works fine except that it doesn't get saved and i know i am missing something and i tried reading a lot of people's problem with the same issue but it didn't work, so if any of you guys could help me i would be highly appreciate it

Answer Source

You can do this in your Variables class so your coins are always saved in a persistent file:

class Variables {

    static let userDefaults = UserDefaults.standard

    struct Constants {
        static let CoinsCollectedKey = "CoinsCollected"

    static var CoinsCollected: Int {
        get {
            return userDefaults.integer(forKey: self.Constants.CoinsCollectedKey)

        set(value) {
            userDefaults.setValue(value, forKey: self.Constants.CoinsCollectedKey)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download