If a Codable Type has a Protocol property that is also Codable, encoding/decoding requires a significant amount of boilerplate code and/or changing the Protocol property to instead be a Type Erasure property.
Root issue being that a Protocol does not conform to itself, so the Protocol property does not itself conform to Codable. This blocks the Codable synthesis of the parent class.
There is also the additional problem of needing to encode/decode unique properties of each Protocol adoptee.
The solutions to this issue are outlined in the excellent answer here:
- The Codable Protocol Property in the parent object can be changed to a Codable Type Erasure, with additional code to handle the unique properties of each Protocol member type.
- Optionally, the parent object can transform the property to the type erasure in its encode/decode methods so that the original property can remain of the Protocol Type.
Opening this improvement ticket for a future version of Swift to hopefully synthesize or otherwise automatically handle Codability of Protocol properties.
Example of issue for playground: