Incorrect code in Listing 20.36

Listing 20.36 shows the following code:

func fetchImage(for photo: Photo,
                completion: @escaping (Result<UIImage, Error>) -> Void) {

    let photoURL = photo.remoteURL
    let request = URLRequest(url: photoURL)

    let task = session.dataTask(with: request) {
        (data, response, error) in

        let result = self.processImageRequest(data: data, error: error)
        OperationQueue.main.addOperation {
            completion(result)
        }
    }
    task.resume()
}

However, the previous changes that we made to this code took place in Listing 20.32, and show that the code should look like this:

func fetchImage(for photo: Photo,
                completion: @escaping (Result<UIImage, Error>) -> Void) {
    guard let photoURL = photo.remoteURL else {
        completion(.failure(PhotoError.missingImageURL))
        return
    }
    let request = URLRequest(url: photoURL)

    let task = session.dataTask(with: request) {
        (data, response, error) in

        let result = self.processImageRequest(data: data, error: error)
        completion(result)
    }
    task.resume()
}

You can see that Listing 20.36 is missing some of the code that we added in Listing 20.32. I believe that in Listing 20.36, the following line…

let photoURL = photo.remoteURL

…should still read as follows:

guard let photoURL = photo.remoteURL else {
        completion(.failure(PhotoError.missingImageURL))
        return
    }

It’s an omission that gave me a moment of confusion as I was working through the chapter. I did confirm in the solutions files for this book that by the end of this lesson, that method should indeed be using the version of that code that has the guard statement. So watch out when you get to this section and don’t get confused.