Swift Codable Protocol: An Introduction

Roman
4 min readMar 19, 2023

The Swift programming language is known for its easy-to-use and efficient syntax. One of its most powerful features is the Codable protocol. Codable is a protocol that provides a simple and efficient way to encode and decode data into different formats such as JSON, XML, and Property List. In this article, we’ll dive into the basics of Codable and explore some of its most prominent benefits and hidden features.

Symbolic picture of JSON formatted text.
Photo by Ferenc Almasi on Unsplash

What is Codable?

Codable is a protocol that was introduced in Swift 4. It combines two other protocols, Encodable and Decodable, which were previously separate. The Encodable protocol defines the methods required to encode an object into a format such as JSON or XML, while the Decodable protocol defines the methods required to decode that format back into an object.

By adopting the Codable protocol, a Swift object can be encoded or decoded with just a few lines of code. This is because the Codable protocol provides default implementations of the Encodable and Decodable protocols.

Basic Usage of Codable

Let’s start with a simple example. Consider the following struct:

struct Person: Codable {
var name: String
var age: Int
}

To encode an instance of this struct into JSON, we can simply create an instance of a JSONEncoder and call its encode method:

let person = Person(name: "Alice", age: 25)
let encoder = JSONEncoder()
let encodedData = try encoder.encode(person)

This will produce a Data object containing the encoded JSON data. To decode this data back into a Person object, we can create an instance of a JSONDecoder and call its decode method:

let decoder = JSONDecoder()
let decodedPerson = try decoder.decode(Person.self, from: encodedData)

This will produce a new instance of the Person struct with the same name and age as the original person object.

Benefits of Codable

  • Efficiency: Codable is built into the Swift standard library, which means that it is highly optimized for performance. The default implementations provided by the protocol are designed to be as efficient as possible, so you can encode and decode data with minimal overhead.
  • Type safety: Codable makes it easy to work with complex data types, while still ensuring that your code is type-safe. By defining your own structs and classes that conform to the Codable protocol, you can ensure that your code is both easy to read and easy to maintain.
  • Interoperability: Codable makes it easy to work with data from different sources, including JSON, XML, and Property List. This means that you can easily integrate your Swift code with other platforms and systems.

(Not So) Hidden Features of Codable

  • Custom Coding Keys: The Codable protocol provides default coding keys based on the properties of your object. However, you can also provide your own custom coding keys if you need to encode or decode your object using different names or formats. You can do this by implementing the CodingKey protocol.
struct Person: Codable {
var name: String
var age: Int

enum CodingKeys: String, CodingKey {
case name = "person_name"
case age = "person_age"
}
}
  • Conditional Conformance: You can make your custom structs and classes conform to Codable conditionally. This means that you can define different encoding and decoding strategies based on the state of your object. You can do this by implementing the encode(to:) and decode(from:) methods yourself.
struct Person {
let name: String
let age: Int
let isEmployed: Bool
}

extension Person: Codable {
enum CodingKeys: String, CodingKey {
case name
case age
case isEmployed
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)

if let isEmployed = try container.decodeIfPresent(Bool.self, forKey: .isEmployed) {
self.isEmployed = isEmployed
} else {
self.isEmployed = false
}
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(age, forKey: .age)

if isEmployed {
try container.encode(isEmployed, forKey: .isEmployed)
}
}
}

Conclusion

In conclusion, the Swift Codable protocol is a powerful and easy-to-use framework for encoding and decoding data in Swift. It allows developers to easily convert data between different formats, such as JSON or binary, and Swift objects. The protocol is highly flexible and customizable, allowing for conditional conformance and custom encoding and decoding strategies.

By implementing Codable in your Swift code, you can achieve many benefits, such as reduced boilerplate code, increased interoperability with external APIs and data formats, and improved type safety. With Codable, you can focus on building your app’s core functionality while letting the protocol handle the heavy lifting of data encoding and decoding.

Overall, the Swift Codable protocol is an essential tool for any Swift developer working with data. Its ease of use, flexibility, and customizability make it a key component in building robust and scalable Swift applications.

--

--

Roman

Day time product owner and night time developer.