arrays - How to Store Nested Arrays in @AppStorage for SwiftUI
问题描述
@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)))
}
}
}
}
推荐阅读
- python - ImportError:无法导入名称“convert_kernel”
- exception - 如何在 .NET CORE 中使用 SqlException?
- amazon-web-services - 在 S3 中,通过具有不同访问级别的 IAM 策略将文件夹分配给两个用户
- haskell - Haskell QuickCheck 用于测试 n-ary tree eval
- mysql - Mysql:带边框的ST_Contains检测多面体是否包含点
- android - 在 recyclerView 中加载项目后如何敬酒?
- android - 所有 com.android.support 库必须使用完全相同的版本规范。找到版本 28.0.0、26.1.0
- php - 添加字符串的合并数组
- python - 使用 Pandas 列绘图
- python - 多个机器人文本以 python/flask/jquery 响应