问题描述
我正在尝试将词典词典保存到UserDefaults.
I am trying to save a dictionary of dictionaries to 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")
但是当我尝试检索它时:
But when I try to retrieve it:
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')
I get an error: Cannot convert value of type '[Int : [Int : Int]].Type' to expected argument type '[AnyClass]' (aka 'Array')
是否可以在UserDefaults中存储[Int:[Int:Int]]字典?还是我必须使用其他方法?
Is there a way to store a [Int:[Int:Int]] Dictionary in UserDefaults? Or I have to use other aproach?
推荐答案
您可以简单地使用JSONEncoder
和JSONDecoder
进行编码,因为Dictionary<Int,Dictionary<Int,Int>>
符合Codable
.
You can simply use JSONEncoder
and JSONDecoder
to do the encoding, since Dictionary<Int,Dictionary<Int,Int>>
conforms to 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]]
在处理实数值而不是这些硬编码的数值时,请勿使用强制展开.
Don't use force unwrapping when working with real values rather than these hard coded ones.
这篇关于如何将字典词典保存为UserDefaults [Int:[Int:Int]]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!