May 18, 2020

Introduction to UserDefaults in swift

By Mohit Agrawal

Basics about UserDefaults in Swift iOS.

iOS default

Introduction to UserDefaults in Swift

Why UserDefaults in swift? You are developing an iOS mobile application and you want to store some data like a bool value ( isUserLoggedIn ) to represent if the current user is logged in or logged out then how will you do this? For this type of purpose, apple provides us UserDefaults. It is used to store only a small amount of data like small string, app status, some imported flags.

Apple says:
An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.

Usage

UserDefaults are used to store data of type Bool, Dictionary, Int, URL, String, Data. The concept of saving and retrieving the data are the same for all data types. So let’s see how to store and retrieve the data.

Saving the bool value to UserDefaults

UserDefaults.standard.set(true, forKey: "isUserLoggedIn")

It takes the two parameters. First is the value which we want to save and the second parameter is the key. This key should be unique because we use this key only to retrieve the data back from the UserDefaults.

Retrieving the bool value

let userLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")

As you can see here I am using the same key “isUserLoggedIn” to retrieve the data from the UserDefaults. If the key does not exist then it will return false by default. Let’s see one more example of saving Int.

Saving integer value to UserDefaults

UserDefaults.standard.set(3, forKey: "LoginAttempt")

Here I am saving an integer value using the key “LoginAttempt”.

Retrieving the integer value

let loginAttempt = UserDefaults.standard.integer(forKey: "LoginAttempt")

Conclusion

UserDefaults are the easiest way of saving data in iOS applications. It automatically initializes as soon as the app loads into the memory. iOS handles everything we just need to save and retrieve the data.

Check out the difference between value type and reference type in swift ?

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!