我正在尝试为我的应用程序构建一个网络层,以便我完成该项目
我遇到了错误
"Cannot invoke 'decode' with an argument list of type '(Codable, from: Data)'" I think its happening because of error type or a mismatch Help me resolve this issue
enum Type:String {
case GET
case POST
case PUT
case DELETE
}
func networkRequest(MethodType:Type, url:String, codableType:Codable) {
guard let getUrl = URL(string: url) else {return}
if MethodType == Type.GET {
URLSession.shared.dataTask(with: getUrl) { (data, response, err) in
if let urlRes = response as? HTTPURLResponse{
if 200...300 ~= urlRes.statusCode {
guard let data = data else {return}
do {
let newData = try JSONDecoder().decode(codableType.self, from: data)
}
catch let jsonerr {
print("Error Occured :"+jsonerr.localizedDescription)
}
}
}
}.resume()
}
}
最佳答案
泛型可以解决这个问题。
首先,引入一个泛型类型参数:
func networkRequest<T: Decodable>(MethodType:Type, url:String)
^^^^^^^^^^^^^^
现在您可以使用 T.self
作为要解码的类型:
try JSONDecoder().decode(T.self, from: data)
此外,您可以考虑添加一个完成处理程序,否则您获取的值将丢失:
func networkRequest<T: Decodable>(MethodType:Type, url:String, completionHandler: (T) -> Void)
用法:
networkRequest(MethodType: .GET, url: ...) {
(myStuff: MyType) in
...
}
关于ios - "How to use Codable Protocol for a Networking Layer ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51077362/