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

Jim*_*mmy 1 dictionary ios swift

我正在尝试将字典的字典保存到 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")
Run Code Online (Sandbox Code Playgroud)

但是当我尝试检索它时:

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

我收到错误:无法将类型 '[Int : [Int : Int]].Type' 的值转换为预期参数类型 '[AnyClass]'(又名 'Array')

有没有办法在 UserDefaults 中存储 [Int:[Int:Int]] 字典?或者我必须使用其他方法?

Dáv*_*tor 5

您可以简单地使用JSONEncoderJSONDecoder进行编码,因为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]]
Run Code Online (Sandbox Code Playgroud)

当使用真实值而不是这些硬编码值时,不要使用强制展开。