ios - 带有 clousers 的泛型错误,即 '(Any) -> Void' 不可转换为 '(T) -> Void

标签 ios swift

我将泛型与 @escaping 闭包一起使用,但在 completion(JSON) 上出现错误 -

'(Any) -> Void' is not convertible to '(T) -> Void'

下面是我试过的代码

static func getData<T>(inputUrl:String,parameters:[String:Any],completion:@escaping(_: T)->Void){
        let url = URL(string: inputUrl)
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in

            let nilValue = ""
            if let JSON = response.result.value {

                completion(JSON)
            }
            else {
                completion(nilValue)
            }
        }
    }

最佳答案

问题是您没有在代码中的任何地方使用泛型类型T,您只是返回一个Any 类型的值,而不管 的类型>T.

如果您真的希望您的函数是通用的,您应该将 response.result.value 转换为 T 并在完成处理程序中返回该值。此外,在失败的情况下不要返回空字符串,让闭包接受一个可选的并在失败的情况下返回 nil

static func getData<T>(inputUrl:String,parameters:[String:Any],completion:@escaping(_: T?)->Void){
    let url = URL(string: inputUrl)
    Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in
        if let json = response.result.value as? T {
            completion(json)
        }
        else {
            completion(nil)
        }
    }
}

关于ios - 带有 clousers 的泛型错误,即 '(Any) -> Void' 不可转换为 '(T) -> Void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46279885/

相关文章:

iOS 12/13 程序化 View 创建

objective-c - 在 Swift 中使用未解析的标识符 'MapTasks'

ios - 是否可以将 PayPal 与适用于 iOS 应用程序的 Parse.com 连接?

javascript - 为什么在 IOS 上选择 List.Accordion 时会以白色突出显示?

ios - 基于引用子文件夹创建唯一数组

iphone - UITextchecker用哪种语言进行拼写检查?

iOS 图表 : Select the data point programmatically but get the highLight is NAN

ios - UITabBarController 内 UINavigationController 的 UINavigationBar 中缺少按钮的插图

ios - 水平 Collection View 在单元格上方有空间。如何删除它?

ios - 类属性未在 Swift 2 中的闭包内分配