Wednesday, September 18, 2019

Serializing Heterogenous Arrays With Codable

Nick Lockwood:

Something I’ve spent time on recently is the problem of serializing heterogenous arrays (arrays containing multiple types) in Swift using Codable.

Here’s a pattern I’ve found that works pretty well, using a protocol and a type-erased wrapper.

Normally in Swift you do polymorphism by either using a protocol or an enum (for open or closed sets, respectively). This approach requires you to use both, which is slightly odd, and it inherently only supports closed sets, but it’s relatively little code to add new cases.

[…]

The other disadvantage is that containing types must use Array<AnyFoo> rather than Array<Foo>, otherwise they can’t use automatic Codable synthesis.

This is necessary because, unlike NSCoding, Codable does not store the type information in the archive. It has to be provided when decoding.

Drew McCormack:

I used a similar approach when messing with genetic programming last year. Began with a switch like you, but in the end went to a dictionary mapping of types.

Ian Keen:

If the underlying format doesn’t matter I have a fairly nice generic solution here.

the DecodingRoutine is just a wrapper around Decodable.inits that you’d normally create specific boxes for. And the ones I’ve provided take advantage of the fact AV cases without values are functions

Comments RSS · Twitter

Leave a Comment