Working with UserDefaults in Swift - A Beginner's Guide

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
June 3, 2024

Working with UserDefaults in Swift

UserDefaults is a simple and efficient way to store small pieces of data persistently on the device. This can be useful for saving user preferences, settings, or any other data that needs to be accessed across app launches. In this tutorial, we will explore how to work with UserDefaults in Swift.

Setting and Retrieving Data

To save data to UserDefaults, you can use the set method with a specific key:

// Saving data to UserDefaults
UserDefaults.standard.set("John Doe", forKey: "username")}

To retrieve the data stored in UserDefaults, you can use the object(forKey:) method:

// Retrieving data from UserDefaults
if let username = UserDefaults.standard.object(forKey: "username") as? String {
    print("Username: \(username)")
}

Checking for Existing Data

You can check if a value exists for a particular key in UserDefaults using the objectForKey method. If the value is nil, it means that no data is stored for that key:

if UserDefaults.standard.object(forKey: "username") == nil {
    print("No username saved in UserDefaults")
}

Removing Data

To remove data from UserDefaults, you can use the removeObject(forKey:) method:

// Removing data from UserDefaults
UserDefaults.standard.removeObject(forKey: "username")}

Working with Complex Data Types

You can also store complex data types such as arrays, dictionaries, and custom objects in UserDefaults by using the set method with the appropriate type:

// Saving an array to UserDefaults
let favorites = ["Apple", "Banana", "Orange"]
UserDefaults.standard.set(favorites, forKey: "favorites")

// Retrieving the array from UserDefaults
if let savedFavorites = UserDefaults.standard.array(forKey: "favorites") as? [String] {
    print("Favorites: \(savedFavorites)")
}

Remember that UserDefaults should not be used to store sensitive information such as passwords or tokens. It is best suited for small, non-sensitive data that needs to persist between app launches.