我正在尝试创建一个函数,该函数根据要传递给它的自定义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'
发布评论