A Binary Coder for Swift
This coder serializes fields by writing them out sequentially as raw bytes, with no metadata.
[…]
Now we can see why I implemented
BinaryEncoder’sencodemethod with a bigswitchstatement instead of using separate implementations for all of the various supported types. Overloaded methods are resolved at compile time based on the static type that’s available at the call site. The above call toencoder.encode(value)will always callfunc encode(_ encodable: Encodable)even if the actual value passed in is, say, aDoubleor aBool. In order to allow for this simple wrapper, the implementation inBinaryEncoderhas to work with a single entry point, which means it needs to be a bigswitchstatement.[…]
Swift’s new
Codableprotocols are a welcome addition to the language to eliminate a lot of boilerplate code. It’s flexible enough to make it straightforward to use/abuse it for things well beyond JSON and property list parsing. Unsophisticated binary formats such as this are not often called for, but they have their uses, and it’s interesting to see howCodablecan be used for something so different from the built-in facilities. TheEncoderandDecoderprotocols are large, but judicious use of generics can cut down a lot of the repetitive code, and implementation is relatively simple in the end.
See also: HashingSingleValueEncodingContainer, MinimalDecoder (via Stephen Celis).
Previously: Swift.Codable.
Update (2017-07-31): See also: Hacker News.