I have a function that is responsible for making the HTTP requests in the app. Basically, it sets up all the required headers, timeouts, etc... etc...
Then, when the request is complete, I run 2 functions (provided by the developer): whenSuccess
/whenError
(depending on the result of the call) and whenComplete
(regardless the result of the call). I want the last one to be able to receive the result of the whenSuccess
function.
I have the doRequest
function declared as
private func doRequest<S>(whenSuccess: (_ json: JSON?)->(S?),
whenError: (_ description: String)->(),
whenComplete: Optional<(S?)->()>) {
// yada yada yada
}
So, the developer provides a function that gets a JSON
and returns a generic. If the whenError
is called, the whenComplete
is called with nil
as parameter.
I'm invoking it with
doRequest<Int>(whenSuccess: { (json) -> (Int?) in //Cannot specialize a non-generic definition
return 5
}, whenError: { (error) in
}) { (success) in
}
I get the error commented:
Cannot specialize a non-generic definition
Any idea if this can be done and how?
Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.
In Swift you must not explicitly specialize generic functions. Instead, generic functions automatically get specialized via type inference from theirs arguments.
The call you you're trying to make should look like this:
doRequest(whenSuccess: { json -> Int? in
//...
}, whenError: { error in
//...
}, whenComplete: { success in
//...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With