Swift 4.0 Codable — Decoding subclasses, inherited classes, heterogeneous arrays

Tom Stoffer
Sep 18, 2017 · 3 min read

Background

Swift 4.0 has introduced a really helpful API. Codable If you have been following the Swift project and the new features in this version on the language you have probably already heard about it. I ran into some issues when working with some of our REST APIs so wanted to document them here in case other people run into the same situations.

Getting Started

If you are familar with Codable you can skip this sections, if not this is how Apple summarise is on there docs page:

Decoding Heterogeneous Arrays

A heterogeneous array is when you have a piece of JSON which contains multiple different objects. In my case, these objects are subclasses of a base class Drink Each subclass has different attributes which need to be serialised.

Models

Serialisation

Heterogenous Array

Summary

This last step was the only way I could get the Decodable API to do my bidding. As far as I can see there is no way to get a decoder from an UnkeyedDecodingContainer or KeyedDecodingContainer This seems like a limitation of the API, but Im sure there are good reasons for it not to be possible. It does seem a little strange to expose that dependency just for this use case of decoding.

Full Playground

TSEngineering

Posts from our engineers

TSEngineering

Posts from our engineers

Tom Stoffer

Written by

TSEngineering

Posts from our engineers