"How to use Codable Protocol for a Networking Layer "
"How to use Codable Protocol for a Networking Layer "
我正在尝试为我的应用构建一个网络层,以便我完成项目
我遇到错误
"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()
}
}
JSONDecoder
需要符合 Decodable
的具体类型。协议不能符合自身。
您可以使该方法通用
func networkRequest<T : Decodable>(MethodType: Type, url: String, codableType: T.Type) {
...
let newData = try JSONDecoder().decode(T.self, from: data)
并称之为
networkRequest(MethodType: .GET,
url: "https://test.com/api",
codableType: News.self)
泛型可以解决这个问题。
首先介绍一个泛型类型参数:
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
...
}
我正在尝试为我的应用构建一个网络层,以便我完成项目
我遇到错误
"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()
}
}
JSONDecoder
需要符合 Decodable
的具体类型。协议不能符合自身。
您可以使该方法通用
func networkRequest<T : Decodable>(MethodType: Type, url: String, codableType: T.Type) {
...
let newData = try JSONDecoder().decode(T.self, from: data)
并称之为
networkRequest(MethodType: .GET,
url: "https://test.com/api",
codableType: News.self)
泛型可以解决这个问题。
首先介绍一个泛型类型参数:
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
...
}