DevPrep

All topics › Real interview tasks

Code review: a completion-based network layer — five interviewer questions

Middle PRO

Task

A candidate wrote a network layer. The code works. What will the interviewer ask, and what should you answer?

final class APIClient {
    private let session: URLSession

    init(session: URLSession = .shared) { self.session = session }

    func request<T: Decodable>(_ request: URLRequest,
                               completion: @escaping (Result<T, APIError>) -> Void) {
        let task = session.dataTask(with: request) { data, response, error in
            if let error { completion(.failure(.transport(error))); return }
            guard let http = response as? HTTPURLResponse else {
                completion(.failure(.invalidResponse)); return
            }
            guard (200...299).contains(http.statusCode) else {
                completion(.failure(.http(http.statusCode))); return
            }
            guard let data, !data.isEmpty else {
                completion(.failure(.emptyData)); return
            }
            do {
                completion(.success(try JSONDecoder().decode(T.self, from: data)))
            } catch {
                completion(.failure(.decoding(error)))
            }
        }
        task.resume()
    }
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store