无法通过闭包推断出通用参数"T"

Ste*_*ott 6 generics swift

我在下面有一个静态函数,它将执行一个GET请求然后尝试将数据解析成任何东西<T>.

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

我的问题是如何调用它?

如果我试图像下面那样调用它,我会得到错误 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 }
Run Code Online (Sandbox Code Playgroud)

通过查看这些函数,通常从函数返回的变量中获取它们的类型,就像下面的示例一样.

let result: Response<JsonResponse> = Notwork.get(url, paramaters: nil, paramaterEncoding: .json)
Run Code Online (Sandbox Code Playgroud)

但是,当结果返回到闭包中时,我该如何指定是什么<T>

谢谢


编辑

下面是一些描述相同问题的示例代码.

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

}
Run Code Online (Sandbox Code Playgroud)

Rah*_*iya 13

调用函数时需要明确告诉类型.如果您期望String,则使用String类型调用它.

MyClass.myFunction { (response: String) in

}
Run Code Online (Sandbox Code Playgroud)