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.
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.
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.
To use Codable with UserDefaults, follow these steps:
Codable protocol.encode(to:) and init(from:) methods to encode and decode your data, respectively.UserDefaults to save and load the data.Let's see this in action with an example!
First, let's create a simple model called Task.
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.
Now, let's see how to encode a Task instance to JSON.
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 taskDecoding a Task from JSON is just as easy.
let decoder = JSONDecoder()
let data = // ... some JSON data
let decodedTask = try! decoder.decode(Task.self, from: data)Now that we can encode and decode tasks, let's see how to save and load tasks using UserDefaults.
// 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)
}Which protocol does the `Task` struct conform to?
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! 🚀🤖✨