如何将字典词典保存为UserDefaults [Int:[Int:Int]]?

时间:2018-09-17 10:51:06

标签: ios swift dictionary

我正在尝试将词典词典保存到UserDefaults。

我可以这样保存字典:

var dict = [Int:[Int:Int]]()
dict[1] = [4:3]
dict[10] = [5:10]

let data = try 
NSKeyedArchiver.archivedData(withRootObject: dict, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "dict")

但是当我尝试检索它时:

if let data2 = defaults.object(forKey: "dict") as? NSData {
let dict = NSKeyedUnarchiver.unarchivedObject(ofClasses: [Int:[Int:Int]], from: data2)
print(dict)
}

我得到一个错误:无法将类型'[Int:[Int:Int]]。Type'的值转换为预期的参数类型'[AnyClass]'(aka'Array')

是否可以在UserDefaults中存储[Int:[Int:Int]]词典?还是我必须使用其他方法?

2 个答案:

答案 0 :(得分:3)

由于JSONEncoder符合JSONDecoder,因此您可以简单地使用Dictionary<Int,Dictionary<Int,Int>>Codable进行编码。

var dict = [Int:[Int:Int]]()
dict[1] = [4:3]
dict[10] = [5:10]

let encodedDict = try! JSONEncoder().encode(dict)

UserDefaults.standard.set(encodedDict, forKey: "dict")
let decodedDict = try! JSONDecoder().decode([Int:[Int:Int]].self, from: UserDefaults.standard.data(forKey: "dict")!) //[10: [5: 10], 1: [4: 3]]

在处理实数值而不是这些硬编码的数值时,请勿使用强制展开。

答案 1 :(得分:1)

我尝试使用Swift 4.1,并且以下方法正常工作。

    var dict = [Int:[Int:Int]]()
    dict[1] = [4:3]
    dict[10] = [5:10]

    let data = try NSKeyedArchiver.archivedData(withRootObject: dict)
    UserDefaults.standard.set(data, forKey: "dict")

正在检索:

    if let data2 = UserDefaults.standard.object(forKey: "dict") as? Data {
        let dict = NSKeyedUnarchiver.unarchiveObject(with: data2)
        if let dic = dict as? [Int:[Int:Int]] { print(dic) }
    }
相关问题