Swift 3 User Defaults

The UserDefaults (formerly NSUserDefaults) is a great way to quickly and easily save persistent data through the lifespan of the app. So in other words, these variables get saved as long as the app hasn’t been deleted. So for example, you might ask for a user’s name, then save it so every time they open the app, the name appears.

Declare a defaults variable in your class. For example…

1

2

3

4

classGameScene:SKScene{

//declare the defaults...

let defaults:UserDefaults=UserDefaults.standard

You’ll notice we used let instead of var above. Totally fine, even though we are setting values for the defaults, you can use let.

Setting Values to the Standard UserDefaults

Now we can save a Bool value to the defaults like so…

1

defaults.set(true,forKey:"HasAppBeenOpenedBefore")

Or I could have saved a String variable like so…

1

defaults.set("Totally True",forKey:"HasAppBeenOpenedBefore")

Other than the value differing, the two lines of code are the same. And if you’re coding in Xcode you’ll notice as soon as you write defaults.set, the code hints suggest all sorts of values, but each is written the same way: value first, followed by the key.

The keys are always String values. Which means for you gamers out there, you can save level specific details by combing strings. So for example, if you had a String variable for currentLevel you could do something like this…

1

defaults.set(true,forKey:currentLevel+"TreasureOpenedAlready")

So you might run a line of code like that after retrieving the treasure on a particular level. And if you tested that value when the level was first entered, you could keep players from retrieving the same treasure twice.

Getting Values from the Standard UserDefaults

Retrieving values is just as easy. It does help to know the type of value that was saved previously. For example, to test what the bool value previously saved was, we would write…

1

iflet opened:Bool=defaults.bool(forKey:"HasBeenOpenedBefore")

You could also test for saved values using…

defaults.integer(forKey: )

defaults.string(forKey: )

defaults.double(forKey: )

defaults.array(forKey: )

defaults.dictionary(forKey: )

defaults.data(forKey: )

And more! So you can see how easy it is to save nearly any type of data to the Standard User Defaults!