【问题标题】:Swift 4 JSONDecoder Utility Function for Arbitrary Struct用于任意结构的 Swift 4 JSONDecoder 实用函数
【发布时间】:2019-08-29 00:43:56
【问题描述】:

我正在尝试创建一个实用函数,它给出了一些 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)

【问题讨论】:

    标签: ios json swift swift4 jsondecoder


    【解决方案1】:

    你可以试试

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-11-05
      • 2019-06-02
      • 2018-09-28
      • 2018-05-07
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多