Search code examples
iosswiftnsdictionaryunwrap

How can I safely unwrap deeply nested values in a dictionary in Swift?


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"?

enter image description here


Solution

  • 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.