尝试编写用于将 JSON 解析为可编码结构的通用函数

Trying to write a generic function for parsing JSON into codable Structs

我目前正在这样解析 JSON

struct ExampleStruct : Codable {
     init() {

     }
     // implementation
}

if let jsonData = jsonString.data(using: .utf8) {
    do {
        let decoder = JSONDecoder()
        let object =  try decoder.decode(ExampleStruct.self, from: jsonData)
    } catch {
        print("Coding error - \(error)")
    }
}

这很好用,但是我周末一直在努力学习泛型。我正在尝试编写一个方法,我传入一个 Codable 结构类型和一个 JSON 字符串,returns 我想要返回的类型的对象。

我尝试了以下方法:-

func getType<T>(_ anyType: T.Type, from jsonString:String) -> T? {

if let jsonData = jsonString.data(using: .utf8) {
    do {
        let decoder = JSONDecoder()
        let object =  try decoder.decode(anyType, from: jsonData)//Errors here
        return object as? T
        return nil
    } catch {
        print("Coding error - \(error)")
       return nil
    }
  }
return nil
}

然后当我想做上面的事情时

 if let exampleStruct:ExampleStruct = getType(type(of: ExampleStruct()), from: jsonString) {
  print(exampleStruct)
 }

但是在 let = object 行我得到以下错误

Cannot convert value of type 'T' (generic parameter of global function 'getType(:from:)') to expected argument type 'T' (generic parameter of instance method 'decode(:from:)')

In argument type 'T.Type', 'T' does not conform to expected type 'Decodable'

正如我所说,本周末我一直在尝试学习泛型,但显然我的理解遇到了障碍。有没有解决这个问题的办法,这确实是我正在尝试做的事情,甚至可能还是一个好主意?

首先,强烈建议将 throwing 函数的错误交给调用者。
其次,从 UTF8 字符串创建的 Data 永远不会失败。

您必须将泛型类型限制为 Decodable,不需要将类型作为额外参数传递。

你的函数可以简化为

func getType<T : Decodable>(from jsonString:String) throws -> T {
    let jsonData = Data(jsonString.utf8)
    return try JSONDecoder().decode(T.self, from: jsonData)
}