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 Property
and Property
.
The implementation details
of these types, however,
are obfuscated by translation logic from
JSONSerialization
and Property
.
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 Single Value Container: Single Value Encoding Container
class Unkeyed Container: Unkeyed Encoding Container
class Keyed Container<Key>: Keyed Encoding Container Protocol
where Key: Coding Key
}
protocol FormatEncoding Container: class {}
#Decoder Structure
public class FormatPack Decoder {
public func decode<T>(_ type: T.Type,
from data: Data) throws -> T
where T : Decodable
}
final class _FormatDecoder: Decoder {
class Single Value Container: Single Value Decoding Container
class Unkeyed Container: Unkeyed Decoding Container
class Keyed Container<Key>: Keyed Container
where Key: Coding Key
}
protocol FormatDecoding Container: 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.