Member-only story
Swift 4.2 Decodable: Heterogeneous collections 📚
Following last year’s release of the Codable protocol, many iOS-developers have been busy removing heavy, custom JSON parsers and replacing them with a smooth and lightweight conformation to Decodable, in the model layer… And I am no exception: In a recent project for a client, I had the joy of enhancing the model layer of a large application with one of the goals being a complete conformation to Codable.
Challenge 1: Nested heterogeneous collections
The transition to Decodable initially went smooth (“happy days when you get to remove code!”). But the removal of the custom JSON parsers resulted in the removal of vital class-type mapping — something that is not directly supported by the otherwise powerful Codable
protocol.
To give an example of what I am talking about, consider the following:
In this very simple case we have a superclass, Pet,
that is inherited by the two classes Cat
and Dog
, allowing a Person to have a single collection of superclass type Pet
with the actual objects in the…