Skip to content

Error creating a generic function to decode array of Decodable object #78

@macshodan

Description

@macshodan

Hi,

I'm struggling with an error when trying to use a generic function to decode an array of objects conforming to the Decodable protocol. The function works when used to decode a single object but then I try to use it for arrays the compiler generate an error (it works fine on iOS obviously).

@inline(__always) private func fetchData<T: Decodable>(_ type: T.Type, request: URLRequest) async throws -> T {
        
        let session = URLSession.shared
        
        let (data, response) = try await session.data(for: request)
        
        guard let response = response as? HTTPURLResponse else {
            throw NetworkError.invalidURL
        }
        
        let statusCode = response.statusCode
        
        if statusCode == 401 {
            throw NetworkError.unauthorized
        }
        
        if let contentType = response.value(forHTTPHeaderField: "Content-Type") {
            if contentType == "application/json" {
                do {
                    let decoded = try decoder.decode(T.self, from: data)
                    return decoded
                } catch {
                    print(error)
                    throw NetworkError.decodingError(error.localizedDescription)
                }
            }
        }
        
        throw NetworkError.invalidStatusCode(statusCode)
    }

This is the generic function I'm using, basically it's a network wrapper api I'm using to simplify network calls. I'm using like this:

let dto: [DTO] = try await fetchData([DTO].self, request: request)

while it compile and works fine on iOS, I get the following skip compile error:

/Users/simo/Library/Developer/Xcode/DerivedData/SchoolbusEasy-hkvmapefknvfiqeabqesbtjwvixq/Build/Intermediates.noindex/BuildToolPluginIntermediates/oimmei-schoolbus-easy.output/SchoolbusEasy/skipstone/SchoolbusEasy/src/main/kotlin/schoolbus/easy/NetworkingService.kt:104:48 Argument type mismatch: actual type is 'KClass<Array<*>>', but 'KClass<Decodable & Array>' was expected.

It works fine if I try to decode a single object instead of an array.

Do you have any ideas on how to solve this, or it simply cannot be done?

thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions