Codable with UserDefaults: Swift Tutorial 🎯

beginner
15 min

Codable with UserDefaults: Swift Tutorial 🎯

Welcome to this in-depth Swift tutorial on using Codable with UserDefaults! In this lesson, we'll learn how to save and load custom data using Swift's built-in UserDefaults and Codable protocol. This is a fundamental skill for any iOS developer and will help you create apps that can persist data even when the app is closed.

What is UserDefaults? 📝

UserDefaults is a powerful, built-in key-value storage system in Swift. It allows you to save and retrieve user preferences, settings, and other data, even across app launches. This is useful for storing data that doesn't need to be synced with a server, such as user preferences or temporary data.

What is Codable? 💡

The Codable protocol in Swift allows you to encode and decode custom data types as JSON or other formats. This is crucial when working with UserDefaults, as it enables you to save and load complex data structures like arrays, dictionaries, and custom classes.

Getting Started 📝

To use Codable with UserDefaults, follow these steps:

  1. Make your class conform to the Codable protocol.
  2. Implement the encode(to:) and init(from:) methods to encode and decode your data, respectively.
  3. Use UserDefaults to save and load the data.

Let's see this in action with an example!

Example: Saving a Simple Model 🎯

First, let's create a simple model called Task.

swift
struct Task: Codable { let title: String let description: String let isCompleted: Bool // Custom initializer init(title: String, description: String, isCompleted: Bool) { self.title = title self.description = description self.isCompleted = isCompleted } }

In this example, we have a Task struct that conforms to the Codable protocol. It has three properties: title, description, and isCompleted. We also added a custom initializer to make it easy to create instances of Task.

Encoding a Task 🎯

Now, let's see how to encode a Task instance to JSON.

swift
let task = Task(title: "Buy milk", description: "Get milk from the store", isCompleted: false) let encoder = JSONEncoder() encoder.encode(task) // This will return Data containing the encoded JSON representation of the task

Decoding a Task 🎯

Decoding a Task from JSON is just as easy.

swift
let decoder = JSONDecoder() let data = // ... some JSON data let decodedTask = try! decoder.decode(Task.self, from: data)

Saving and Loading a Task with UserDefaults 🎯

Now that we can encode and decode tasks, let's see how to save and load tasks using UserDefaults.

swift
// Save a task let taskData = try! JSONEncoder().encode(task) UserDefaults.standard.set(taskData, forKey: "task") // Load a task if let taskData = UserDefaults.standard.object(forKey: "task") as? Data { let decodedTask = try! JSONDecoder().decode(Task.self, from: taskData) print(decodedTask) }

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Which protocol does the `Task` struct conform to?

Conclusion 📝

In this tutorial, we learned how to use Codable with UserDefaults to save and load custom data in Swift. This is a powerful combination that will help you create apps that can persist data even when the app is closed.

Remember to always make your classes conform to Codable and implement the encode(to:) and init(from:) methods to encode and decode your data. Then, use UserDefaults to save and load the data as needed.

Happy coding! 🚀🤖✨