简体   繁体   中英

Swift 4.2 : Type 'T' does not conform to protocol 'Decodable'

I have a function calling an URL to receive data as JSON. To decode JSON to a custom class I use JSONDecoder.

fileprivate func loadFlux<T>(_ typeClass: T.Type, urlCriteria url: String) -> Promise<Any> {

    var dataFlux: [T]? = nil
    var promise: Promise<Any>? = nil

    ...

    let jsonData: Data = try! JSONSerialization.data(withJSONObject: data as! NSArray)

    let decoder = JSONDecoder()
    dataFlux = try decoder.decode([T], from: data)

    ...
}

Before installing the last version of Xcode and swift 4.2, the code build without any issue.

But now I obtain the following error message : Type 'T' does not conform to protocol 'Decodable' on the line :

dataFlux = try decoder.decode([T], from: data)

I tried to googled the message but without any success for now. Any suggestion to solve that issue ?

That code could not have compiled even on a previous Swift version, since JSONDecoder.decode expects its input argument to conform to Decodable and you have no type constraints set up. You simply need to restrict T to Decodable .

fileprivate func loadFlux<T:Decodable>(_ typeClass: T.Type, urlCriteria url: String) -> Promise<Any> {

    var dataFlux: [T]? = nil
    var promise: Promise<Any>? = nil

    ...

    let jsonData: Data = try! JSONSerialization.data(withJSONObject: data as! NSArray)

    let decoder = JSONDecoder()
    dataFlux = try decoder.decode([T].self, from: jsonData)

    ...
}

Without full context I cannot tell for sure what are you returning from your function, but returning Promise<Any> from a generic function definitely seems like a bad idea. You should rather make the return type of the function generic as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM