ios - "How to use Codable Protocol for a Networking Layer "

标签 ios swift encoding swift4 decoding

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

我正在尝试为我的应用程序构建一个网络层,以便我完成该项目

我遇到了错误

"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/

相关文章:

ios - Xcode UI 测试 - 多个 UITableView

ios - 创建端到端 iOS 应用程序时,应该先创建前端还是后端?

ios - 理解SDWebImage下载器

git - 如何在 Ubuntu 和 Windows 上为 German Umlaute 配置 git 编码?

C# HttpListener 响应 + GZipStream

ios - 1 为企业和 App Store 打造的应用程序

ios - Image.xcassets 问题显示 iOS 8 设备的启动画面

ios - 尝试插入 10000 条记录 sqlite ios swift

swift - CLLocationCoordinate2D 到一个数组

javascript - 解码使用 JS encodeURIComponent 函数编码的参数