我在UserDefaults保存和分享扩展所需嵌套的字典。这本字典的结构如下图所示:
let dict = [
"Sections" : [
["Title" : "Title1", "Items": ["item1-1", "item1-2", "item1-3"]],
["Title" : "Title2", "Items": ["item2-1", "item2-2", "item2-3", "item2-4"]],
["Title" : "Title3", "Items": ["item3-1"]],
]
]
与成功保存:
UserDefaults(suiteName: "group.identifier.test")!.setValue(dict, forKey: "savedDict")
但现在我希望把它找回来,并检查是标题2已经存在,如果是,那么将其删除,并用新的项目再次添加
我以前做以下,但不能拿到冠军回来:
let savedDict:[String:AnyObject] = UserDefaults(suiteName: "group.identifier.test")!.object(forKey: "savedDict") as! Dictionary
成功通过下面的代码获取“节”下的数据
let savedSection = savedDict["Sections"]
print("Saved Section: \(savedSection)")
但无法与拿到冠军:
print("Saved Title: \(savedSection!["Title"])") *// return nil*
我试过(键,值)太多,但解雇一个数据类型错误
for (key, value) in savedSection{ *// Type 'AnyObject?' does not conform to protocol 'Sequence'*
print("Key: \(key) Value: \(value)")
}
我可以知道有没有什么办法让“标题”回来检查和更新?我使用了错误的方式来存储这种嵌套数据?
非常感谢!
在你的代码
print("Saved Title: \(savedSection!["Title"])") *// return nil*
这里应该是
if let savedSection = savedDict["Sections"] as? [[String : Any]] { //EDIT***
print("Saved Title: \(savedSection[0]["Title"])") *// inplace of 0 any index you want,
}
就好像现在在你的字典中有三个元素,因此它的安全在0中获取价值,希望大家理解的是,底层的字典也代替使用字典,你可以使用结构或类保存在部分关键字典的数组,你数据同时得到它检索它作为结构类型。
首先,从来没有使用KVC方法setValue(:forKey
与UserDefaults
。
有通用set(:forKey
。并且有dictionary(forKey:
获得[String:Any]
字典背
用于键Sections
该值是一个阵列(索引为基础的)。让我们假设你有这样的新数据
let newTitle2 : [String:Any] = ["Title" : "Title2", "Items": ["item4-1", "item4-2", "item4-3"]]
这是加载字典的方式 - 你应该始终安全检查字典存在 - 更新并保存回。如果存在"Title2"
的项目将被覆盖否则新项目被添加到阵列。
let groupDefaults = UserDefaults(suiteName: "group.identifier.test")!
if var savedDict = groupDefaults.dictionary(forKey: "savedDict"),
var sections = savedDict["Sections"] as? [[String:Any]] {
if let title2Index = sections.firstIndex(where: {($0["Title"] as! String) == "Title2"}) {
sections[title2Index] = newTitle2
} else {
sections.append(newTitle2)
}
savedDict["Sections"] = sections
groupDefaults.set(savedDict, forKey: "savedDict")
}