如何编写JSON通用函数?敏捷的

如何编写JSON通用函数?敏捷的,json,swift,generics,jsondecoder,Json,Swift,Generics,Jsondecoder,我有不同的结构作为我的数据模型。 当我想用JsonDecoder().decode解析数据时,我需要在.decoder中设置一个.Type.self(SomeType.self,from:data) 我想写一个支持函数,可以返回正确的类型分别。 像这样的 但我不知道怎么 func check<T>(string: String) -> T if string == "something" { return Something.type } func par

我有不同的结构作为我的数据模型。 当我想用JsonDecoder().decode解析数据时,我需要在.decoder中设置一个.Type.selfSomeType.self,from:data)

我想写一个支持函数,可以返回正确的类型分别。 像这样的 但我不知道怎么

func check<T>(string: String) -> T
if string == "something" {
return Something.type
}

func parseJSON(from data: Data , with address: String)-> Codable? {
let type = check(string: address) 
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(type.self, from: data)
return decodedData
} catch let error {
print(error)
return nil
}
}

您的方法无法工作,您必须使用限制为
Decodable
的泛型类型。在运行时检查字符串不是一种好做法

这是代码的简化版本,错误将移交给调用者

func parseJSON<T : Decodable>(from data: Data) throws -> T {
    return try JSONDecoder().decode(T.self, from: data)
}

或者如果要在函数中指定类型

func parseJSON<T : Decodable>(from data: Data, type : T.Type) throws -> T {
    return try JSONDecoder().decode(T.self, from: data)
}

let result = try parseJSON(from: data, type: [Foo].self)
func parseJSON(来自数据:data,类型:T.type)抛出->T{
返回try JSONDecoder().decode(T.self,from:data)
}
let result=try parseJSON(from:data,类型:[Foo].self)

您的方法无法工作,您必须使用限制为
可解码的泛型类型。在运行时检查字符串不是一种好做法

这是代码的简化版本,错误将移交给调用者

func parseJSON<T : Decodable>(from data: Data) throws -> T {
    return try JSONDecoder().decode(T.self, from: data)
}

或者如果要在函数中指定类型

func parseJSON<T : Decodable>(from data: Data, type : T.Type) throws -> T {
    return try JSONDecoder().decode(T.self, from: data)
}

let result = try parseJSON(from: data, type: [Foo].self)
func parseJSON(来自数据:data,类型:T.type)抛出->T{
返回try JSONDecoder().decode(T.self,from:data)
}
let result=try parseJSON(from:data,类型:[Foo].self)

您有一个字符串告诉您要解码的类型?假设您能够做到这一点,您打算如何使用
parseJSON
返回的解码内容?你所知道的只是它是可编码的。你不能用它做很多事情,是吗?你有一个字符串告诉你要解码什么类型?假设您能够做到这一点,您打算如何使用
parseJSON
返回的解码内容?你所知道的只是它是可编码的。很抱歉,我听不懂你的回答,但我用一个代码补充了我的问题,所有的东西都按照我想要的方式工作,但这会导致代码重复。对不起,我听不懂你的回答,但我用一个代码补充了我的问题,所有的东西都按照我想要的方式工作,但这会导致代码重复