如何在 Swift 的字典中安全地展开深层嵌套的值?
How can I safely unwrap deeply nested values in a dictionary in Swift?
我了解如何打印上层事物的值,例如 "email" 的值或 "name" 的值,但我如何 安全地 展开字典以打印更深的嵌套值,例如 "url"?
的值
像那样:
if let picture = dictionary["picture"] as? [String:AnyObject] {
if let url = picture["url"] as? String {
}
if let width = picture["width"] as? Int {
}
}
嵌套只是意味着您的顶级 [String: Any]
字典中特定键的值是另一个 [String: Any]
- 因此您只需要转换它来访问嵌套对象。
// assuming you have an object `json` of `[String: Any]`
if let pictureJSON = json["picture"] as? [String: Any] {
// if the JSON is correct, this will have a string value. If not, this will be nil
let nestedURL = pictureJSON["url"] as? String
}
我觉得我应该提一下Swift中serializing/de-serializingJSON的过程与Swift中的Codable有了很大的飞跃 4.如果你有一个模型对象你想将这个 JSON 映射到,这整个事情都可以自动完成(包括嵌套对象 - 你只需提供一个符合 Codable 的嵌套 Swift struct/class )。 Here's some Apple documentation on it.
我了解如何打印上层事物的值,例如 "email" 的值或 "name" 的值,但我如何 安全地 展开字典以打印更深的嵌套值,例如 "url"?
的值像那样:
if let picture = dictionary["picture"] as? [String:AnyObject] {
if let url = picture["url"] as? String {
}
if let width = picture["width"] as? Int {
}
}
嵌套只是意味着您的顶级 [String: Any]
字典中特定键的值是另一个 [String: Any]
- 因此您只需要转换它来访问嵌套对象。
// assuming you have an object `json` of `[String: Any]`
if let pictureJSON = json["picture"] as? [String: Any] {
// if the JSON is correct, this will have a string value. If not, this will be nil
let nestedURL = pictureJSON["url"] as? String
}
我觉得我应该提一下Swift中serializing/de-serializingJSON的过程与Swift中的Codable有了很大的飞跃 4.如果你有一个模型对象你想将这个 JSON 映射到,这整个事情都可以自动完成(包括嵌套对象 - 你只需提供一个符合 Codable 的嵌套 Swift struct/class )。 Here's some Apple documentation on it.