将json解码类型快速传递到http请求
我想创建一个可以返回如下定义的stuct的静态func:将json解码类型快速传递到http请求,json,swift,Json,Swift,我想创建一个可以返回如下定义的stuct的静态func: struct Category: Codable { public let data: Array<CateItem> public let status: Int public let msg: String } static func Get(codePoint: String, responseType: Codable){ let urlString = UrlUtils.GetUrl
struct Category: Codable {
public let data: Array<CateItem>
public let status: Int
public let msg: String
}
static func Get(codePoint: String, responseType: Codable){
let urlString = UrlUtils.GetUrl(codePoint: codePoint)
let url = URL(string: urlString)
let task = URLSession.shared.dataTask(with: url!){
(data,response,error) in
if error != nil{
print(error!)
}else{
if let data = data{
JSONDecoder().decode(responseType, from: data)
}
}
}
task.resume()
}
HttpRequests.Get(codePoint: "getCategoryList", responseType: Category)
然后像这样调用该方法:
struct Category: Codable {
public let data: Array<CateItem>
public let status: Int
public let msg: String
}
static func Get(codePoint: String, responseType: Codable){
let urlString = UrlUtils.GetUrl(codePoint: codePoint)
let url = URL(string: urlString)
let task = URLSession.shared.dataTask(with: url!){
(data,response,error) in
if error != nil{
print(error!)
}else{
if let data = data{
JSONDecoder().decode(responseType, from: data)
}
}
}
task.resume()
}
HttpRequests.Get(codePoint: "getCategoryList", responseType: Category)
但是这里的responseType
不起作用
如何修复此问题?您希望传递的是结构类型,而不是协议 首先,对您的方法进行一般约束,即
T
必须符合Decodable
(因为您需要它只是为了解码,所以不需要符合Encodable
)
然后说参数的类型应该是T.type
-这允许编译器推断T
的类型,您可以避免使用此参数,请参见答案末尾
static func Get<T: Decodable>(codePoint: String, responseType: T.Type) { ... }
然后,当您想调用您的方法时,像在解码中一样传递结构的类型
HttpRequests.Get(codePoint: "getCategoryList", responseType: Category.self)
还请注意,您的调用是异步的,因此要返回数据,您需要将完成处理程序定义为方法的参数
completion: @escaping (T?) -> Void
请注意,方法的名称应以小写字母开头
您还可以避免使用
responseType
参数,因为可以从完成闭包的参数类型推断T
的类型
static func get<T: Codable>(codePoint: String, completion: @escaping (T?) -> Void) { ... }
您要传递的是结构的类型,而不是协议 首先,对您的方法进行一般约束,即
T
必须符合Decodable
(因为您需要它只是为了解码,所以不需要符合Encodable
)
然后说参数的类型应该是T.type
-这允许编译器推断T
的类型,您可以避免使用此参数,请参见答案末尾
static func Get<T: Decodable>(codePoint: String, responseType: T.Type) { ... }
然后,当您想调用您的方法时,像在解码中一样传递结构的类型
HttpRequests.Get(codePoint: "getCategoryList", responseType: Category.self)
还请注意,您的调用是异步的,因此要返回数据,您需要将完成处理程序定义为方法的参数
completion: @escaping (T?) -> Void
请注意,方法的名称应以小写字母开头
您还可以避免使用
responseType
参数,因为可以从完成闭包的参数类型推断T
的类型
static func get<T: Codable>(codePoint: String, completion: @escaping (T?) -> Void) { ... }
顺便说一句,
responseType
参数实际上不是必需的,因为它可以从闭包类型推断出来。虽然很少有希望类型不同的情况。顺便说一句,responseType
参数实际上不是必需的,因为它可以从闭包类型推断出来。虽然很少有情况下您希望类型不同。