如何将Dictionary <String,Any>保存到UserDefaults?

时间:2020-04-20 09:44:43

标签: swift swiftui nsuserdefaults

将字典保存到UserDefaults()时遇到一些困难。

尝试过UserDefaults.standard.set(dict1, forKey: "dict1",但出现错误:

由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“试图插入非财产列表对象

也尝试了NSKeyedArchiver,但此错误弹出:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__ SwiftValue encodeWithCoder:]:无法识别的选择器发送到实例

这是字典:

@State var dict1: Dictionary<String, Any> = [
    "progress": Double(0.5),
    "count": 10,
    "max": 20,
    "name": "dict1",
    "value": Double(10.00),
    "color": Color.green,
    "completed": false,
    "incrament": Double(1)
]

这是Xcode 11 SwiftUI。 有帮助或提示吗?预先谢谢你!

1 个答案:

答案 0 :(得分:0)

        struct LocalData {
        static var myDicts: [dictionary] {
                get {
                    guard let data = UserDefaults.standard.data(forKey: #function) else { return [] }
                    do {
                        let myDict = try JSONDecoder().decode([dictionary].self, from: data)
                        return myDict
                    } catch {
                        print(error)
                    }
                    return []
                }
                set{
                    let data = try! JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: #function)
                    UserDefaults.standard.synchronize()
                }

        }
    }


struct dictionary: Codable {
    var progress: Double?
    var count: Int?
    var max: Int?
    var name: String?
    var value: Double?
    var color: String?
    var completed: Bool?
    var increment: Double?
    }

用法:

var dict: [dictionary] = [dictionary(progress: 10, count: 10, max: 10, name: "mydict", value: 10.5, completed: true, increment: 10.4)]

    LocalData.myDicts = dict
    print(LocalData.myDicts)

对于颜色,您可以执行以下操作:

if LocalData.myDicts[0].color == red {
 self.view.backgroundColor = .red
}else if LocalData.myDicts[0].color == green {
 self.view.backgroundColor = .green
}