Articles, podcasts and news about Swift development, by John Sundell.

Codable logo

Codable

Discover Swift’s Codable protocol, how to fully leverage its compiler synthesis features, and how to use its surrounding APIs to write efficient serialization code.

Let’s start with the basics

Swift’s Codable protocol and its surrounding APIs provide a built-in way to serialize and deserialize Swift values to and and from various formats, including JSON and Plists.

Arguably one of the most appealing aspects of Codable is its tight integration with the Swift compiler, which often makes it possible for the compiler to automatically generate a given type’s encoding and decoding code.

On this Discover page, you’ll find a collection of articles about various techniques, patterns, and features that can help you to make great use of Codable within your Swift programs.

Making full use of Codable’s compiler synthesis

As mentioned above, one of the Codable protocol’s most powerful features is that the compiler is often able to automatically generate a given type’s conformance to it, as long as that type only contains Codable-conforming properties, and as long as the structure of our type perfectly matches the data that we’re looking to encode or decode.

Although Codable does provide a number of ways for us to completely customize that auto-generated serialization logic, sometimes we might be able to slightly tweak our types to better match the way Codable works — which can often lead to simpler code that requires fewer overrides and manual implementations. That’s what the following articles are all about:

Customization

As convenient as code generation is, sometimes we might need to write our own, custom encoding or decoding code to bridge the gap between our Swift types and their serialized representations. Here are a few articles on how to do just that:

Using the power of type inference

Finally, let’s take a look at how Codable can be extended to better utilize Swift’s powerful type system. By default, all types need to be manually specified when decoding a given piece of data, which can feel quite redundant since that information can typically be inferred from the surrounding context.

Thankfully, with just a few extensions, we can leverage Swift’s type inference capabilities to make it easier to start an encoding or decoding process, and to make it more convenient to build custom Codable implementations from scratch.