【问题标题】:Cannot invoke 'decode' with an argument list of type '(T, from: Data)'无法使用类型为“(T,来自:数据)”的参数列表调用“解码”
【发布时间】:2018-02-07 20:31:47
【问题描述】:

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

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

这是用于函数参数中“类型”值的示例模型(为了节省空间而制作得更小):

struct MainDataFamily: Codable {

    let families: [Family]

    enum CodingKeys: String, CodingKey {

        case families = "families"
    }
}

【问题讨论】:

    标签: ios swift generics swift4 codable


    【解决方案1】:

    类型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) { ... }
    

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2015-06-06
      相关资源
      最近更新 更多