UserDefaults in Swift

Suneet Agrawal
2 min readApr 13, 2022

--

A small set of data is required to be stored and accessed very frequently and need to be persisted across sessions or app launches. One way of keeping them is using a local database like core data in an iOS app. But core data is helpful in the case of tables and queries. There is another way to store a small set of data, UserDefaults.

This post was originally posted at https://agrawalsuneet.github.io/blogs/userdefaults-in-swift/ and reposted on Medium on 13th April 2022.

Let’s try to understand what are UserDefaults first.

What is UserDefaults

UserDefault is used to store small pieces of data which can persist across sessions or app launches. Things like auth token, username, emailid, display name which are being used accross the sessions can be store in UserDefaults.

How UserDefaults works

UserDefaults stores data in a key-value pair where the key can be of string type and value can be of Int, Float, Double, Bool, String, Data, URL, Array, Dictionary and much more.

The information will be stored in a .plist format on the local disk.

Currently, there is no size limit to store data in UserDefaults but it’s usually preferred for the small size of data only.

How to use UserDefaults

In order to use the UserDefaults, first, get the standard UserDefault object.

let defaults = UserDefaults.standard

standard is a global instance of NSUserDefaults or which only getter is exposed. We can’t set any reference to it.

/**
+standardUserDefaults returns a global instance of NSUserDefaults configured to search the current application's search list.
*/
open class var standard: UserDefaults { get }

Write data to UserDefaults

We can set the value for any key using set function on UserDefault.standard object. The set method has multiple overloads that have the same signature but takes different parameters as a value along with a String key.

let defaults = UserDefaults.standard//String Value
defaults.set("Suneet Agrawal", forKey: "stringKey")
//Int Value
defaults.set(1, forKey: "integerKey")
//Double Value
defaults.set(30.0, forKey: "doubleKey")
//Array Value
defaults.set([1,2,3], forKey: "intArrayKey")

Please continue reading at https://agrawalsuneet.github.io/blogs/userdefaults-in-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--