Lessons and Playgrounds Code Snippets for Swift 3, Sprite Kit, and Xcode 8

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…

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…

Or I could have saved a String variable like so…

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.

Using the UserDefaults in Swift 3

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…

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…

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!

How to Print Out All Values in the UserDefaults with Swift 3

 

Ready for hundreds of hours of iOS and tvOS video tutorials, Starter Kits and a lot more Swift fun?

Visit CartoonSmart.com