Flight School

DIY Codable Encoder / Decoder Kit

Create your own Swift Codable encoders and decoders

In Swift 4, a type that conforms to the Codable protocol can be encoded to or decoded from representations for any format that implements a corresponding Encoder or Decoder type.

At the time of its release, the only reference implementations for these types were the Foundation framework’s JSONEncoder / JSONDecoder and PropertyListEncoder and PropertyListDecoder. The implementation details of these types, however, are obfuscated by translation logic from JSONSerialization and PropertyListSerialization.

The DIY Codable Encoder / Decoder Kit repository on GitHub makes it easier for developers to create encoders and decoders for custom formats. The template includes stubbed placeholders for the required types and methods as well as simple tests for encoding and decoding Codable types.

Just do a find-and-replace for the format name and rename a few files, and you can get right into the nitty-gritty of your format’s specific implementation details.

Encoder Structure

public class <#Format#>Encoder {
    public func encode<T>(_ value: T) throws -> Data
                        where T : Encodable

class _<#Format#>Encoder: Encoder {
    class SingleValueContainer: SingleValueEncodingContainer
    class UnkeyedContainer: UnkeyedEncodingContainer
    class KeyedContainer<Key>: KeyedEncodingContainerProtocol
            where Key: CodingKey

protocol <#Format#>EncodingContainer: class {}

Decoder Structure

public class <#Format#>PackDecoder {
    public func decode<T>(_ type: T.Type,
                          from data: Data) throws -> T
                        where T : Decodable

final class _<#Format#>Decoder: Decoder {
    class SingleValueContainer: SingleValueDecodingContainer
    class UnkeyedContainer: UnkeyedDecodingContainer
    class KeyedContainer<Key>: KeyedContainer
            where Key: CodingKey

protocol <#Format#>DecodingContainer: class {}

For an example of this template in action, see this Codable-compatible encoder and decoder for the MessagePack format.

We’d love to see what you make with this! Please get in touch via Twitter to share your custom encoder or decoder.

If you’re interested in learning more, check out The Flight School Guide to Swift Codable.