Serialization in Swift

I wrote an experimental Swift encode / decode package (similar to Codable at interface level) that does not treat reference types as second-class citizens.

I called it GraphCodable. You can check it here.

GraphCodable:

  • encodes type information;
  • supports reference types inheritance;
  • never duplicates the same object (as defined by ObjectIdentifier);
  • in other words, it preserves the structure and the types of your model unaltered during encoding and decoding;
  • is fully type checked at compile time;
  • supports keyed and unkeyed coding, also usable simultaneously;
  • supports conditional encoding;
  • implements an userInfo dictionary;
  • implements a type version system;
  • implements a type substitution system during decode;

The package comes with a fairly complete documentation with many examples, a table summarizing the coding rules, a description of the data format.

I think you might find interesting the two examples concerning the encoding and decoding of DAG (Directed Acyclic Graph) and DGC (Directed Acyclic Graph).

I can confirm that deferDecode(...) is only required to decode a weak variable used to break ARC memory strong cycles. In any other situation, decode(...) must be used. If you don't believe me, check it out.

The main difficulty, in my opinion, is that you have to keep the types repository (simplifying, a singleton "typeName: GCodable type" dictionary) updated during the development of an application. The absence of a single 'GCodable' type from the types repository makes it impossible to decode a data file containing it.

I see two ways of solving this problem:

  • a compiler magic that auto-register all GCodable types encountered during compilation. Is this possible with generic types?;
  • better yet, a way to serialize and deserialize Any.Type, if possible.

If there is a third one, I would be happy to learn it.

9 Likes