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

。_饼干妹妹 提交于 2019-12-01 07:29:40

问题


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"
    }
}

回答1:


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

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) 

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

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


来源:https://stackoverflow.com/questions/48672744/cannot-invoke-decode-with-an-argument-list-of-type-t-from-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!