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
’sencode
method with a bigswitch
statement 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, aDouble
or aBool
. In order to allow for this simple wrapper, the implementation inBinaryEncoder
has to work with a single entry point, which means it needs to be a bigswitch
statement.[…]
Swift’s new
Codable
protocols 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 howCodable
can be used for something so different from the built-in facilities. TheEncoder
andDecoder
protocols 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.