如何在 SwiftUI 的 @AppStorage 中存储嵌套数组 [英] How to Store Nested Arrays in @AppStorage for SwiftUI
本文介绍了如何在 SwiftUI 的 @AppStorage 中存储嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@AppStorage
最近在 SwiftUI 中被引入,它似乎是 UserDefaults
的替代品.我正在尝试使 @AppStorage
能够存储嵌套列表.
@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
我在处理普通的 UserDefaults 时使用了这个:
I used this while dealing with normal UserDefaults:
@Published var list = UserDefaults.standard.array(forKey: "nestedList") as? [[String]] ?? [[String]]()
长话短说,如何将普通的旧 UserDefuaults
转换为新的属性包装器 @AppStorage
?
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
}
}
这是一个演示:
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)))
}
}
}
}
这篇关于如何在 SwiftUI 的 @AppStorage 中存储嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文