How to pass the type to a completion handler with a generic type

the function declaration is like this

func loadData<T:Codable>(params: parameters,completion: @escaping (resultados) -> Void)

resultados is:

enum resultados{
case datos(Dato: T)
case error(Error: Error)
}
the problem come when calling this function, there is no a effective way to say what the type because the completion is enum with generic that need a type to confort to Codable, but i can find a way to make it.
so calling the function

dataLoader(parms: param,completion:{result in})
here xcode complains since there is no way to infer the type of result Generic parameter 'T' could not be inferred

Actually, there's a way to do it:

dataLoader(parms: param,completion:{(result: MyType) in })

In addition to using the generic context as @mghzawi said, you can also pass a type directly:

func loadData<T: Decodable>(of type: T.Type = T.self, parameters: Parameters, completion: @escaping (Result<T, Error>) -> Void) {

You can then use the function as @mghzawi recommended:

loadData(parameters: params) { (result: Result<String, Error>) in
...
}

Or pass the type:

loadData(of: String.self, parameters: params) { print($0) }

ok thanks for the is really cool

Terms of Service

Privacy Policy

Cookie Policy