R.Ham R.Ham - 8 months ago 31
Swift Question

Swift: How to make a change to a variable load next time the application is opened

I have some global settings variables that are occasionally changed by the user during the apps runtime. I want to make the users change permanent, but at the moment every time the app is then reloaded it reverts to the original values e.g. user changes SettingsVariables.settingTwo to false, but then when the app is rerun the variables value changes back to true (the original value).

import UIKit

struct SettingsVariables {

static var settingOne = 0
static var settingTwo = true



What you need is to create UserDefaults values these will be in the memory even when you close and restart your app.

// Set
UserDefaults.standard.set(123, forKey: "key")
// Get
UserDefaults.standard.integer(forKey: "key")

So basically you could do this in your AppDeletegates applicationWillTerminate.

UserDefaults.standard.set(SettingsVariables.settingOne, forKey: "settingOne")

and then when your app start again you can do

SettingsVariables.settingOne = UserDefaults.standard.integer(forKey: "settingOne")

If you want to use your Struct.

For Swift 2 as you are using, the syntax is this:

// Set
NSUserDefaults.standardUserDefaults().setInteger(123, forKey: "key")
// Get