无法使用类型为((T,from:Data)'的参数列表调用'decode'

编程入门 行业动态 更新时间:2024-10-27 13:28:49
本文介绍了无法使用类型为((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'

本文发布于:2023-11-26 16:37:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型   列表   Data   decode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!