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.
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
Asked: 2023-07-17 18:06:57 +0000
Seen: 10 times
Last updated: Jul 17 '23
How to add a custom button in SwiftUI for iOS13 that enables going back between screens?
How can the update of properties from both ParentViewModel and ChildViewModel in SwiftUI be solved?
Can SwiftUI be utilized to restrict the touch region for a drag gesture?
How can the color of a selected element (Picker) be modified in SwiftUI for WatchOS?
How to make a calendar layout that is horizontal using Swiftui?
What is the process to add a radio button with a check mark on a TableView cell using Swift?
How to limit UITextField input to only accept numerical values?