Ste Prescott Ste Prescott - 7 months ago 34
Swift Question

Generic parameter 'T' could not be inferred with closures

I have a static function below that will perform a

GET
request and then attempt to parse the data into whatever
<T>
is.

public static func get<T>(url: NSURL, paramaters: [String : AnyObject]?, paramaterEncoding: ParameterEncoding, compleation:(response: Response<T>) -> Void)


My question is how do I call it?

If I attempt to call it like below I get the error of
Cannot explicitly specialize a generic function


let url = NSURL(string: "http://g.co")!
typealias JsonResponse = [String : AnyObject]
Notwork.get<JsonResponse>(url, paramaters: nil, paramaterEncoding: ParameterEncoding.json) { (response) in }


From looking around functions like these normally get their type from the variable that the function returns to just like the example below.

let result: Response<JsonResponse> = Notwork.get(url, paramaters: nil, paramaterEncoding: .json)


However as the result comes back in a closure, how do I specify what
<T>
is?

Thanks




Edit



Below is some sample code that depicts the same problem.

import Foundation

struct MyClass {
static func myFunction<T>(compleation:(response: T) -> Void) {

let apiResponse = ["some" : "value"]

guard let value = apiResponse as? T else {
return
}

compleation(response: value)
}
}

//Gives error "Generic parameter 'T' could not be inferred"
MyClass.myFunction { (response) in

}

Answer

You need to explicitly tell the type when calling the function. If you are expecting String then call it with String type.

MyClass.myFunction { (response: String) in

}