Member-only story

Avoid using codable for API parsing in swift

Codecat15
4 min readMar 1, 2020

--

Codable is a type alias that allows you to encode and decode a structure or a class that inherits from it.

Let’s talk code for a minute

Here EmployeeResponse is a structure that inherits from Decodable and looks like this

And we will use this employee response structure in our API code to decode the response we get from the server as you can see in the highlighted code.

Now we have a good idea of how the code is looking, let’s get back to why codable should not be used for API parsing.

In the code, you can see that we use JSONDecoder decode function to decode the response from the server and return an object.

The decode function as per apple documentation accepts a generic parameter type which should inherit from the Decodable protocol and another parameter is of the type Data, as you can see in the below screenshot

--

--

Codecat15
Codecat15

No responses yet