skiptools / skiptools/skip-foundation
Error creating a generic function to decode array of Decodable object
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 17
- Forks
- 16
- Avg merge
- 1h 50m
- Merged PRs (30d)
- 2
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the generic fetchData call and the generated skipstone/SchoolbusEasy/src/main/kotlin/schoolbus/easy/NetworkingService.kt error at line 104. Compare the generated type handling for a single Decodable value with the [DTO] call, then verify that an array of Decodable objects compiles and can be decoded without the KClass type mismatch.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- mobile-dev
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100