Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic parameter 'T' could not be inferred with closures

Tags:

generics

swift

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 My {
    static func function<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"
My.function { (response) in

}
like image 723
Ste Prescott Avatar asked Apr 25 '16 11:04

Ste Prescott


1 Answers

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

}
like image 105
Rahul Katariya Avatar answered Nov 17 '22 11:11

Rahul Katariya