为什么我的模板不能与JSONDecodable一起使用

时间:2017-11-02 13:30:49

标签: swift templates swift4 codable

我使用新的Swift 4 Codable接口从Web服务中简单地获取JSON数据。我试图实现泛型类型方法来处理解码(所以我不需要自定义方法)但我一直收到错误。这是代码

extension StarWarsAPI {
public func decodeJson<T: Codable>(fetchUrl: URL, modelType: T, completion: @escaping (_ modelObject: Codable?, _ error:StarWarsErrorType?) -> Void){

    //guard modelType is Codable else {return completion(nil,nil)}

    var fetchRequest = URLRequest(url: fetchUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    fetchRequest.httpMethod = "GET"
    fetchRequest.allHTTPHeaderFields = [
        "content-type": "application/json",
        "cache-control": "no-cache",
    ]

    let session = URLSession.shared
    let fetchDataTask = session.dataTask(with: fetchRequest) { (data, response, error) in

        guard error == nil else {
            return  completion(nil, StarWarsErrorType.urlResponseError(error: error))
        }
        guard let httpResponse = response as? HTTPURLResponse else {
            return  completion(nil, StarWarsErrorType.NilUrlResponseError())
        }
        guard let data = data else {
            return  completion(nil, StarWarsErrorType.noDataFound)
        }
        guard httpResponse.statusCode > 199 && httpResponse.statusCode < 300 else {
            return  completion(nil, StarWarsErrorType.httpErrorCode(code: httpResponse.statusCode))
        }
        var modelObject:Codable?
        do {

            let jsonDecoder = JSONDecoder()
            modelObject = try jsonDecoder.decode(modelType.self, from: data)
            return completion(modelObject, nil)
        }catch{ // do nothing }

            DispatchQueue.main.async {
                completion(nil, nil)
            }
        }
    }

    fetchDataTask.resume()
}

错误读取&#34;无法调用&#39;解码&#39;使用类型&#39;(T,from:Data)的参数列表&#39;&#34; 。这是错误的屏幕截图。

我错过了什么?谢谢!

enter image description here

1 个答案:

答案 0 :(得分:2)

传递给decode(_:from:)的类型需要静态知道。 modelType.selfmodelType的动态实例,但其类型不受静态约束;您需要使用T.self,这是一种静态类型。