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