With API I'm working with, I have a case where 1 API Endpoint can return completely different responses, based on if the call was successful or not.
In case of success, API Endpoint returns an Array of requested objects, in the root, something like this:
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
...
]
which I'm normally decoding with try JSONDecoder().decode([Object].self, from: data)
In case of an error, API Endpoint returns something completely different, looks like this:
{
"error": "value1",
"message": "value2",
"status": "value3"
}
and decoding with try JSONDecoder().decode([Object].self, from: data)
normally fails.
Now, my question is, is there a way, to decode error response keys, in this kind of (I would say not so normally architectured API), WITHOUT creating a -what I call- plural object named Objects
that would have optional properties error
, message
, status
, and for example objects
.
My thinking got somewhere to extending Array where Element == Object
and somehow trying to decode error
, message
, status
, but I'm hitting Conformance of 'Array<Element>' to protocol 'Decodable' was already stated in the type's module 'Swift'
. Maybe it's not even possible to do it that way, so any other, even completely different, suggestion would be very welcome.
let objectsAPI = APIRouter<[Object]>()
– Leucippus