如何访问嵌套字典?

时间:2018-02-03 17:42:49

标签: swift dictionary

我可以在调试器中打印它:

(lldb) print params["message"]!
([String : String]) $R5 = 2 key/value pairs {
  [0] = (key = "body", value = "iPadUser has started a new stream")
  [1] = (key = "title", value = "Stream started")
}

但我想弄清楚如何分别访问正文和标题。

我用这种方式构建params:

            let recipients = ["custom_ids":[recips]]
            let notificationDetails = "hello there"
            let content = [
                "title":title,
                "body":details
            ]
            let params: [String:Any] = [
                "group_id":"stream_requested",
                "recipients": recipients,
                "message": content
            ]

1 个答案:

答案 0 :(得分:0)

print((params["message"] as! [String: Any])["title"] as! String)

您需要将Dictionary值转换为特定类型,因为编译器不知道会发生什么。 (请注意,除了示例代码之外,您不能以其他方式使用强制解包。)

考虑到收件人字典如下所示需要获取数组值:

let recipients = ["custom_ids":["recipe1", "recipe2", "etc"]]

这样的ids:

guard let recipients = params["recipients"] as? [String: Any],
      let customIDs = recipients["custom_ids"] as? [String] 
else { return }

for id in customIDs {
    print(id) // Gets your String value
}