“如何将可编码协议用于网络层”

时间:2018-06-28 07:41:59

标签: ios swift encoding swift4 decoding

How to resolve this issue.......

我正在尝试为我的应用构建网络层,以便在完成项目时

我遇到错误

  

“无法使用类型为'(Codable,from:Data)'的参数列表调用'decode''”,我认为是由于错误类型或不匹配而导致的,请帮我解决此问题

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()

    }

}

2 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:1)

泛型可以解决这个问题。

首先,引入一个通用类型参数:

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
    ...
}