Swift - cannot specialize in nonequivalent definitions

I have a function that is responsible for executing HTTP requests in an application. Basically, it sets all the necessary headers, timeouts, etc. Etc .... Then, when the request is completed, I run 2 functions (provided by the developer): whenSuccess / whenError (depending on the result of the call) and whenComplete (regardless of the result of the call). I want the latter to be able to get the result of the whenSuccess function.

I have a 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 receives JSON and returns a generic one. If whenError is whenError , whenComplete is called with the nil parameter.

I call it with

 doRequest<Int>(whenSuccess: { (json) -> (Int?) in //Cannot specialize a non-generic definition return 5 }, whenError: { (error) in }) { (success) in } 

I get an error message:

It is impossible to specialize not a general definition

Any idea if this can be done and how?

+6
source share
1 answer

In Swift, you should not explicitly specialize common functions. Instead, general functions automatically become specialized by type inference from their arguments.

The call you are trying to make should look like this:

 doRequest(whenSuccess: { json -> Int? in //... }, whenError: { error in //... }, whenComplete: { success in //... }) 
+8
source

Source: https://habr.com/ru/post/1013933/


All Articles