本文介绍了如何在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?

推荐答案

您需要做的就是使用:

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中存储嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 07:41