无法使用类型为((T,from:Data)'的参数列表调用'decode' [英] Cannot invoke 'decode' with an argument list of type '(T, from: Data)'

查看:96
本文介绍了无法使用类型为((T,from:Data)'的参数列表调用'decode'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数根据要传递给它的自定义JSON模型采用类型为 Codable的参数。错误:

I'm trying to create a function that takes in a parameter of type 'Codable' based on the custom JSON models being passed to it. The error :

 Cannot invoke 'decode' with an argument list of type '(T, from: Data)'

在解码行上出现,这是函数:

happens on the decode line, here is the function:

static func updateDataModels <T : Codable> (url: serverUrl, type: T, completionHandler:@escaping (_ details: Codable?) -> Void) {

guard let url = URL(string: url.rawValue) else { return }

URLSession.shared.dataTask(with: url) { (data, response, err) in

    guard let data = data else { return }

    do {
        let dataFamilies = try JSONDecoder().decode(type, from: data)// error takes place here

        completionHandler(colorFamilies)

    } catch let jsonErr {
        print("Error serializing json:", jsonErr)
        return
    }
    }.resume()
}

这是用于函数参数中类型值的示例模型(减小尺寸以节省空间) :

This is what a sample model to be used for the 'type' value in the function's parameters (made much smaller to save space):

struct MainDataFamily: Codable {

    let families: [Family]

    enum CodingKeys: String, CodingKey {

        case families = "families"
    }
}


推荐答案

T 类型的类型是其元类型 T.Type ,因此必须将
函数参数声明为 type:T.Type

The type of the type T is its metatype T.Type, therefore the function parameter must be declared as type: T.Type.

您可能还想使完成句柄采用 T 类型的参数,而不是 Codable

You may also want to make the completion handle take a parameter of type T instead of Codable:

static func updateDataModels <T : Codable> (url: serverUrl, type: T.Type,
         completionHandler:@escaping (_ details: T) -> Void) 

调用函数时,使用 .self 将类型作为
参数传递:

When calling the function, use .self to pass the type as an argument:

updateDataModels(url: ..., type: MainDataFamily.self) { ... }

这篇关于无法使用类型为((T,from:Data)'的参数列表调用'decode'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆