UserDefaults with Codable in Swift

Start with UserDefaults | How to use UserDefaults?

Ahmed Adam
2 min readJan 21, 2021

Most of the time we need to save some small data locally on our devices so the first option comes to our minds is the UserDefaults.

I will illustrate in this article how to deal with UserDefaults.

What is UserDefaults?

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

The types of dataUserDefaults accepts

UserDefaults supports saving data like Int String Bool Data Array Dictionary

Saving data Syntax

UserDefaults.standard.set(value, forKey: "key")

for example saving and retrieving a String

//SaveUserDefaults.standard.set("Your String", forKey: "give a key name")//RetrieveUserDefaults.standard.string(forKey: "The key you used in saving")//RemoveUserDefaults.standard.removeObject(forKey: "Key")

Note your key must be unique if you save data with the same key it is going to override last value in that key, so be sure that’s your key is unique.

Highly recommended is to separate yours keys string in a variables and use these variables.

An example to save your custom object inside UserDefaults using Codable.

This example to save custom object the favorite follower into the UserDefaults and retrieve this object, As you know we can’t save any data types except the data introduced above.

Save

  1. The Function accept array of the follower type and return error optional if there is an error
  2. Encoding our array of followers with JSONEncoder() to convert it to data so that UserDefaults can accept it.
  3. Save this encoded data to UserDefaults
  4. If encoding failed we return the Custom error

Retrieve

  1. As you can see made a variable for the key called “favorites”.
  2. retrieveFavorites func takes two parameters array of [Follower] and the Custom error.
  3. Trying to retrieve the data from the UserDefaults using our key.
  4. Decoding this data to our custom object
  5. If decoding failed then retrieve our custom error

The Custom Object Follower

The Custom Error

Conclusion

Dealing with UserDefaults is pretty easy, but you to be cautious to get the best performance just deal with small scale of data, And when dealing with a larger scale, You should consider think of Core Data or Realm.

--

--

Ahmed Adam
Ahmed Adam

Written by Ahmed Adam

Senior iOS Engineer | Swift | SwiftUI | Objective-C | Agile | Scrum | Mobile Development |

Responses (1)