Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Cannot specialize a non-generic definition

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?

like image 695
Miguel Ribeiro Avatar asked Jan 10 '17 09:01

Miguel Ribeiro


People also ask

What are generics Swift?

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.


1 Answers

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
    //...
})
like image 124
werediver Avatar answered Sep 18 '22 17:09

werediver