【发布时间】:2019-08-29 00:43:56
【问题描述】:
我正在尝试创建一个实用函数,它给出了一些 Data 和一个符合 Decodable 的 struct 可以将 JSON 数据解码为如下结构:
func decodeDataToModel(data : Data?, model : Decodable) -> Decodable? {
guard let data = data else { return nil }
let object : Decodable?
do {
object = try JSONDecoder().decode(model, from: data)
} catch let decodeErr {
print("Unable to decode", decodeErr)
}
return object
}
这会引发错误:Cannot invoke decode with an argument list of type (Decodable, from: Data)。如何使此函数与可以作为模型传递的任意结构一起使用?
例如,如果我有:
struct Person : Decodable {
let id : Int
let name: String
}
struct Animal : Decodable {
let id : Int
let noOfLegs: Int
}
我希望能够像这样使用它
let animal = decodeDataToModel(someData, from: Animal.self)
let human = decodeDataToModel(someOtherData, from: Person.self)
【问题讨论】:
标签: ios json swift swift4 jsondecoder