Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The Swift Fetch method can be modified using Generics in the following way:

func fetch<T: Codable>(url: URL, completion: @escaping (Result<T, Error>) -> Void) {

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard error == nil else {
            completion(.failure(error!))
            return
        }

        guard let data = data else {
            completion(.failure(FetchError.noData))
            return
        }

        do {
            let decoder = JSONDecoder()
            let result = try decoder.decode(T.self, from: data)
            completion(.success(result))
        } catch {
            completion(.failure(error))
        }
    }.resume()
}

enum FetchError: Error {
    case noData
}

The modifications include: - Adding a generic type parameter T to the function signature, which will enable us to specify the type of Codable object we want to decode from the response data. - Instead of using a specific type like User to decode the response data, we use the T type parameter with the JSONDecoder's decode method. - Changing the completion handler's result type to Result<T, Error> to match the type parameter we added. This will allow the caller to handle success and error cases with the specific type of object they're expecting. - Adding an enum FetchError to handle the case where no data is returned from the API.