@AppStorage
was introduced in SwiftUI recently, it seems like an alternative to UserDefaults
.
I'm trying to make the @AppStorage
able to store nested lists.
For simple cases, you would do
@AppStorage("selected") var selected = 0
I used this while dealing with normal UserDefaults:
@Published var list = UserDefaults.standard.array(forKey: "nestedList") as? [[String]] ?? [[String]]()
Long story short, how do I convert plain old UserDefuaults
to the new property wrapper, @AppStorage
?
All you need is to conform Array
to RawRepresentable
using the extension from here:
extension Array: RawRepresentable where Element: Codable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode([Element].self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return "[]"
}
return result
}
}
Here is a demo:
struct ContentView: View {
@AppStorage("items") var items: [[String]] = [
["1", "2"],
["a", "b", "c"],
]
var body: some View {
VStack {
Text("items: \(String(describing: items))")
Button("Add item") {
items[0].append(String(Int.random(in: 1...10)))
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With