Search code examples
swiftcodableswift-protocolsdecodable

Type cannot conform to Decodable but it actually is


I have a Type called ObjectAPIModel that explicitly conforms to the Codable protocol. I also do have a function which receives some data and calls another function to decode any JSON to a specified type. But if I call decodeJSON() it shows an error that ObjectAPIModel does not conform to Decodable. Can anyone help?

struct ObjectAPIModel: Codable {
    
    let objectID: Int
    var primaryImage: String
    var title: String
    var department: String
}
func decodeJSON<T: Decodable>(data: Data, ofType: T) -> Result<T, APIError> {
        
    let decodedObject = try? JSONDecoder().decode(T.self, from: data)
    if decodedObject == nil {
        return .failure(APIError.emptyResponse)
    } else {
        return .success(decodedObject!)
    }
}
let result = decodeJSON(data: unwrappedData, ofType: ObjectAPIModel)

Error I receive: "Type 'ObjectAPIModel.Type' cannot conform to 'Decodable'"


Solution

  • In the following line

    func decodeJSON<T: Decodable>(data: Data, ofType: T) -> Result<T, APIError>
    

    the parameter ofType is declared to be an instance of T and you are trying to pass the type meta object. Change the declaration as follows:

    func decodeJSON<T: Decodable>(data: Data, ofType: T.Type) -> Result<T, APIError>
    //                                                  ^^^^
    

    Also, when you call decodeJSON you can't use a bare type name, you have to put ObjectAPIModel.self i.e.

    let result = decodeJSON(data: unwrappedData, ofType: ObjectAPIModel.self)
    //                                                                  ^^^^