我正试着把字典的字典保存到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’(又名'Array')
有办法在UserDefaults中存储[Int:Int:Int]字典吗?还是我要用其他的方法?
发布于 2018-09-17 10:58:12
您只需使用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]]当使用实际值时,不要使用强制展开,而不要使用这些硬编码值。
发布于 2018-09-17 11:02:08
--我尝试了使用WASTIVE4.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) }
}https://stackoverflow.com/questions/52366070
复制相似问题