Ste Prescott Ste Prescott - 2 years ago 99
Swift Question

Generic parameter 'T' could not be inferred with closures

I have a static function below that will perform a

request and then attempt to parse the data into whatever

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: "")!
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



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 {

compleation(response: value)

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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download