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 FormatEncoder {
    public func encode<T>(_ value: T) throws -> Data
                        where T : Encodable

class _FormatEncoder: Encoder {
    class SingleValueContainer: SingleValueEncodingContainer
    class UnkeyedContainer: UnkeyedEncodingContainer
    class KeyedContainer<Key>: KeyedEncodingContainerProtocol
            where Key: CodingKey

protocol FormatEncodingContainer: class {}

Decoder Structure

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

final class _FormatDecoder: Decoder {
    class SingleValueContainer: SingleValueDecodingContainer
    class UnkeyedContainer: UnkeyedDecodingContainer
    class KeyedContainer<Key>: KeyedContainer
            where Key: CodingKey

protocol FormatDecodingContainer: 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.