Saving an Array of Codable Objects in SwiftUI’s @AppStorage
As we know SwiftUI’s @AppStorage
property wrapper is a convenient way to persist simple data types like strings, integers, and booleans across app launches. However, it doesn’t natively support more complex data types like arrays or custom objects. In this article, we’ll explore a solution for storing an array of Codable objects using @AppStorage
.
In this article, we’ll explore a solution for storing an array of Codable objects using @AppStorage
.
Imagine you have a custom Codable struct called Task
that represents a to-do item, and you want to store an array of these tasks using @AppStorage. The straightforward approach of using @AppStorage("tasks") var tasks: [Task] = []
won't work because @AppStorage expects a property wrapper over a type that conforms to the RawRepresentable protocol.
But to make our array of Codable objects work with @AppStorage
, we need to create a RawRepresentable extension for Array where the Element type conforms to Codable. This extension will handle the encoding and decoding of the array to and from a String, which is the type expected by @AppStorage
.
extension Array: RawRepresentable where Element: Codable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try…