Ask Your Question
3

How can the Swift Fetch method be modified using Generics?

asked 2023-07-17 18:06:57 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-17 18:08:02 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-17 18:06:57 +0000

Seen: 10 times

Last updated: Jul 17 '23