Passing the Photos Around

Let’s finish parsing the photos. Open FlickrAPI.swift and implement a method that takes in an instance of Data and uses the JSONDecoder class to convert the data into an instance of FlickrResponse.

Listing 20.21  Decoding the JSON data (FlickrAPI.swift)

static func photos(fromJSON data: Data) -> Result<[Photo], Error> {
    do {
        let decoder = JSONDecoder()
        let flickrResponse = try decoder.decode(FlickrResponse.self, from: data)
        return .success(flickrResponse.photosInfo.photos)
    } catch {
        return .failure(error)
    }
}

If the incoming data is structured JSON in the form expected, then it will be parsed successfully, and the flickrResponse instance will be set. If there is a problem with the data, an error will ...

Get iOS Programming: The Big Nerd Ranch Guide, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.