The future of serialization & deserialization APIs

One of the big flaws of Codable is that it was built on the wrong abstraction. 99.9% of the time, developers who are interested in serializing a struct to data and back are doing so to a single, well-known format. However, the Codable API was built so that the abstraction point is the encoder itself, under the assumption that you would want to serialize a type to multiple formats. This is not the case.

That design flaw has been the #1 source of Codable's woes. It makes properly implementing custom coders almost impossible; no one implements superEncoder properly, since most people don't deal with inheritance of reference types, and some formats are fundamentally incompatible with the Encoder/Decoder APIs. (XML and CSV are two that spring to mind off the top of my head)

There are two main kinds of serialization that types need to do:

  1. Serialization to-and-from a specific format
  2. Serialization to-and-from an opaque format

Codable tries to do both and, from what I can tell, this proposal is aiming to replace it with something that also tries and does both. I think that's a mistake. IMO we should be encouraging packages that provide format-specific coders (JSONCodable, PlistCodable, CSVCodable, XMLCodable, etc) so that each encoder and decoder can provide format-specific functionality. Then we should provide a system level API to ask types to encode into an opaque format (ie "please turn yourself into a Data and back again").

So I'm very interested in the @JSONCodable macros provided in the example... but those should be part of a JSON-specific package. And if I truly want a single struct that can be encoded to JSON and XML and ProtoBuf and CSV, then I should have to indicate that separately on the struct by conforming to each of those separate protocols.


Edit: or to put it more plainly... Foundation should provide an updated replacement for NSCoding and leave the type-specific encoders to type-specific packages to implement.

46 Likes