ios - 在 UserDefaults 中保存嵌套字典并管理重复检查 [Swift 4.2]
问题描述
我有一个嵌套字典需要保存在 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")
但现在我想取回它并检查 Title2 是否已经存在,如果是,则删除它并再次添加新项目
我曾经做过以下但无法取回标题:
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,
}
好像现在在您的字典中,section 中有三个元素,因此可以安全地获取 0 的值,希望您了解底层字典是 section 键中的字典数组,也可以使用 struct 或 class 来保存您的而不是使用字典数据并在获取它时将其作为该结构类型检索。
推荐阅读
- javascript - 为什么使用无状态功能组件而不是基于类的组件?
- java - 构建任务和 sourceCompatibility = 1.7, gradle 5.3 的问题
- ssl - 如何在 Go 中建立与 memsql 的基于 ssl 的 tcp 连接
- ruby-on-rails - 调用model.save有什么效果!在 save_change_to_attribute 的 after_create 回调中?在 after_save 回调中?
- rest - 使用 Retry-After 标头响应非 503/3xx
- c++ - 在 C++ 中用于树数据结构的方法链接期间传递的相同地址?
- c++ - 错误:“decltype”之前的预期主表达式
- ios - AppCenter POD:没有这样的文件或目录
- mysql - 在mysql中使用索引字段删除很慢
- ios - Twilio 远程视图 (TVIVideoView) 在接收方为空白