Swift 4 任意结构的 JSONDecoder 实用函数

Swift 4 JSONDecoder Utility Function for Arbitrary Struct

我正在尝试创建一个效用函数,给定一些 Data 和一个符合 Decodablestruct 可以将 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)

你可以试试

func decodeDataToModel<T:Decodable>(data : Data?,ele:T.Type) -> T? {
    guard let data = data else { return nil } 
    do {
        let object = try JSONDecoder().decode(T.self, from: data)
        return object
    } catch  {
        print("Unable to decode", error)
    }
    return nil
}

通话

let animal = decodeDataToModel(data:<#animaData#>, ele: Animal.self)