Decoding an array containing multiple types in swift

Theodore Gonzalez
WanderCodes
Published in
1 min readMar 28, 2020

--

There are some cases where servers will send an array of multiple objects that are very different from each other.
For example: A ride share business like RideAustin, Uber or Grab, where they drive for passengers and at the same time they have deliver food and packages.

An order history is a list that may contain one or all of these deliveries

Only the `totalCost` and `date` are common between the three.

Some people might be tempted to handle this by having a GenericOrderItem that conforms to Codable.

It is easy to write but I don’t like this approach because all the other fields that are not common will become optional.

It is not clear for future readers that some values are always available for certain types.

For example, restaurantName will always be there when you order food.

You must throw errors when these types of variables are missing.

So my preferred solution was to have an enum and use a custom decoder only for this enum.

FoodDelivery, PackageDelivery and PassengerDelivery are simply conforming to Codable

See the test for how the result looks

A decoding error will be thrown when none of the deliveries are available

But an empty list is decoded successfully

A decoding error will be thrown when the restaurantName is nil just by conforming to Codable

This way when a new developer looks at FoodDelivery.swift, he knows exactly what he will expect.

See the project in https://github.com/tedgonzalez/array-of-multiple-objects

--

--