Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

UserDefaults Tutorial

Introduction to UserDefaults

UserDefaults is a simple and efficient way to save user preferences or settings in an iOS application. It allows developers to store small amounts of data persistently across launches of the application. Data stored in UserDefaults is saved to the device’s filesystem and retrieved whenever needed.

Basic Usage

To store data using UserDefaults, you use the UserDefaults.standard singleton. Here’s how to save and retrieve a simple value:

Saving a Value:
UserDefaults.standard.set("John Doe", forKey: "username")
Retrieving a Value:
let username = UserDefaults.standard.string(forKey: "username")

Supported Data Types

UserDefaults supports a variety of data types, including:

  • String
  • Int
  • Float
  • Double
  • Bool
  • URL
  • Array
  • Dictionary

Example: Storing Different Data Types

Storing an Integer:
UserDefaults.standard.set(25, forKey: "age")
Retrieving an Integer:
let age = UserDefaults.standard.integer(forKey: "age")
Storing a Boolean:
UserDefaults.standard.set(true, forKey: "isLoggedIn")
Retrieving a Boolean:
let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")
Storing an Array:
let fruits = ["Apple", "Banana", "Cherry"]
UserDefaults.standard.set(fruits, forKey: "favoriteFruits")
Retrieving an Array:
let favoriteFruits = UserDefaults.standard.stringArray(forKey: "favoriteFruits")

Removing Values

If you need to remove a value from UserDefaults, you can use the removeObject(forKey:) method:

Removing a Value:
UserDefaults.standard.removeObject(forKey: "username")

Checking for Existing Values

Sometimes, you need to check if a value already exists in UserDefaults before attempting to retrieve it:

Checking Existence:
if UserDefaults.standard.object(forKey: "username") != nil {
    // Value exists
} else {
    // Value does not exist
}

Synchronizing UserDefaults

Although UserDefaults automatically synchronizes data, you can manually trigger synchronization by calling the synchronize() method. This is rarely necessary but can be useful in some cases:

Manual Synchronization:
UserDefaults.standard.synchronize()

Conclusion

UserDefaults is a powerful tool for persisting small amounts of data in iOS applications. It is straightforward to use and supports various data types. By understanding how to store, retrieve, and manage data using UserDefaults, you can significantly enhance the user experience in your app.