How do I prevent the triangle of doom when accessing JSON Data?

时间:2015-09-01 21:17:08

标签: ios swift

I am traversing some JSON Data where I need to access nested elements. Currently the easiest way is manually traverse the JSON Data as dictionaries like so

typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>

if let jsonData = data["preview"] as? JSONDictionary {
    if let source: JSON = jsonData["images"] as? JSONArray {
        if let images = source[0] as? JSONDictionary {
            if let image = images["source"] as? JSONDictionary {
                if let url = image["url"] as? String {
                    self.imageURL = url
                    getPhoto()
                }
            }
        }
    }
}

This seems unsustainable and the code is ugly. Is there a better way to do this? How can I better traverse JSON data?

1 个答案:

答案 0 :(得分:4)

Try this using multiple levels seperated by commas:

if let
    jsonData = data["preview"] as? JSONDictionary,
    source   = jsonData["images"] as? JSONArray,
    images   = source[0] as? JSONDictionary,
    image    = images["source"] as? JSONDictionary,
    url      = image["url"] as? String
{
    self.imageURL = url
    getPhoto()
}