Codable-DIY-Kit

by Flight-School

Flight-School / Codable-DIY-Kit

A template for creating your own Swift Codable encoders and decoders

201 Stars 7 Forks Last release: Not found MIT License 7 Commits 0 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

DIY Codable Encoder / Decoder Kit

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
.

This repository provides a template that 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.

This general structure was used to implement a

Codable
-compatible encoder and decoder for the MessagePack format.

For more information about the design and implementation of custom encoder and decoder types, see Chapter 7 of Flight School Guide to Swift Codable.

Usage

  • Clone this repository
  • Find all instances of the "<#Format#>" placeholder and replace with the name of your own format
  • Replace the leading underscores in the
    ___Decoder.swift
    and
    ___Encoder.swift
    files, as well as the source files in the Tests directory
  • Run the command
    swift package generate-xcodeproj
    in the root project directory
  • Fill in the missing implementation accordingly

Encoder Structure

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

final class _Encoder: Encoder { final class SingleValueContainer: SingleValueEncodingContainer final class UnkeyedContainer: UnkeyedEncodingContainer final class KeyedContainer: KeyedEncodingContainerProtocol where Key: CodingKey }

protocol EncodingContainer: class {}

Decoder Structure

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

final class _Decoder: Decoder { final class SingleValueContainer: SingleValueDecodingContainer final class UnkeyedContainer: UnkeyedDecodingContainer final class KeyedContainer: KeyedContainer where Key: CodingKey }

protocol DecodingContainer: class {}

License

MIT

Contact

Mattt (@mattt)

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.