Using Generic parameter in closure

I have a function that makes a service call to fetch data, uses JSONDecoder to decode the JSON response into a model object and then return that object as part of a parameter in the completion block provided to the function. In the object, I am actually using the Result object. Here is the code -

static func fetchData(_ completion: @escaping (Result<ExampleModelObject, Error>) -> Void)

I am trying to make this function generic, where it can accept the url it needs to call as one parameter and the Model object as another parameter and so I modified it to this -

static func fetchData <T: Decodable>(urlString: String, _ completion: @escaping (Result<T, Error>) -> Void)

This is the code where I use jsondecoder -

let parsedJSON = try jsonDecoder.decode(T.self, from: data)
            completion(.success(parsedJSON))

Here is how I am trying to call this function from another class -

DataRetriever. fetchData(urlString: dataURLString) { (result: ExampleModelObject) in

However, I am getting 2 errors during compilation -

  1. Cannot convert value of type '(ExampleModelObject) -> Void' to expected argument type '(Result<_, Error>) -> Void'
  2. Generic parameter 'T' could not be inferred

Would anyone please be able to help me with how I can fix these errors?



Read more here: https://stackoverflow.com/questions/68463656/using-generic-parameter-in-closure

Content Attribution

This content was originally published by learner2010 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: