Codable in Swift

Updated 31 May 2021


Codable is a type alias for the Encodable and Decodable protocols. According to Apple documentation “A type that can convert itself into and out of an external representation”.

Encodable Protocols:- The process in which custom type is converted into other representation is known as encoding or serialization. And to do so encodable protocols have to conform.

Decodable Protocols:- The process in which others’ representation is converted into your custom type is known as decoding¬†or deserialization. And to do so decodable protocols have to conform.

And to support both encoding and decoding Codable protocols have to conform.

Let see an example.

Now Employee type can be encoded and decoded both.


It is used to encode our type to another type. Like converting into data.

Let see an example.

Now, we will encode Employee into data.

when we print the data it prints in Byte.


Now, we will convert the data again into Employee type.

Below is the output of decoding.

If you only want to Encode then you have to conform to Encodable protocol and vice versa.

Coding Keys

If you want to use a different key name in your custom type than the actual JSON key. In that case, we will use CodingKeys enum. And will conforms CodingKey protocol.

Let see an example of it.

Thanks for reading the Codable blog.

You can also check other blogs from here. if you have any issue or suggestion you can leave your query/suggestion in the comment section.



. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home