I have a following struct with generics for API response with pagination:
struct Paginable<Body> {
let data: [Body]
let meta: Meta
}
extension Paginable {
struct Meta: Codable {
let pagination: Pagination
struct Pagination: Codable {
let total: Int
let count: Int
let perPage: Int
let currentPage: Int
let totalPages: Int
}
}
}
And I want to be able to decode it like so:
let response = try? response.decode(to: Paginable<Segment>.self)
So here's my attempt to make it Decodable:
extension Paginable where Body == Data {
func decode<BodyType: Decodable>(to type: BodyType.Type) throws -> Paginable<BodyType> {
guard let decodedJSON = try? JSONDecoder().decode(BodyType.self, from: data) else {
throw APIError.decodingFailure
}
return Paginable<BodyType>(data: decodedJSON, meta: self.meta)
}
}
This gives me two errors:
Cannot convert value of type 'Paginable.Meta' to expected argument type 'Paginable<_>.Meta'
on the line with return statement
If I change the meta property to some primitive type like Int, the error disappears. But Meta itself is Codable, so what's to problem here?
Cannot convert value of type '[Data]' to expected argument type 'Data'
on the line with guard statement
How to solve this one?
Segment. Also theJSONthat you're trying to decode.