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

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

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

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

发生在解码线上,这里是函数:

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()
}

这是用于函数参数中的 'type' 值的示例模型(为了保存 space 而变得更小):

struct MainDataFamily: Codable {

    let families: [Family]

    enum CodingKeys: String, CodingKey {

        case families = "families"
    }
}

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

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

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

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

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