I understand how to print the values of upper level things such as the value of "email" or the value of "name" but how would I safely unwrap the dictionary to print a deeper nested value such as the value of "url"?
Asked
Active
Viewed 941 times
-1
-
Parse the dictionary into a proper Codable structure. – Alexander Feb 28 '18 at 21:07
-
Please post the code as text and not as a photo, that way people can directly copy your code into a playground and test it. – Feb 28 '18 at 22:00
2 Answers
2
Nesting just means that the value for a particular key in your top level [String: Any]
dictionary is another [String: Any]
- so you just need to cast it to access nested objects.
// 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
}
I feel I should mention that the process of serializing/de-serializing JSON in Swift took a big leap with Codable in Swift 4. If you have a model object you want to map this JSON to, this whole thing can be automated away (including nested objects - you just supply a nested Swift struct/class conforming to Codable). Here's some Apple documentation on it.

Connor Neville
- 7,291
- 4
- 28
- 44
0
Like that:
if let picture = dictionary["picture"] as? [String:AnyObject] {
if let url = picture["url"] as? String {
}
if let width = picture["width"] as? Int {
}
}

Jonas
- 21
- 7
-
1Swift native dictionary value type is `Any`. Most Swift types are structures. `AnyObject` can only be used as the concrete type for instances of classes. – Leo Dabus Feb 28 '18 at 20:29
-
I agree with that, however this example comes from a Firebase fetching method where the usage of AnyObject is recommended. – Jonas Feb 28 '18 at 20:49