Serializing Heterogenous Arrays With Codable
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.
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.
If the underlying format doesn’t matter I have a fairly nice generic solution here.
the
DecodingRoutine
is just a wrapper aroundDecodable.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