首页 > 解决方案 > 在 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)")
}

我可以知道有没有办法让“标题”回来检查和更新?我是否使用错误的方式来存储这种嵌套数据?

非常感谢!

标签: iosswiftswift4swift4.2

解决方案


在你的代码中

 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 来保存您的而不是使用字典数据并在获取它时将其作为该结构类型检索。


推荐阅读