Problems with Codable protocol and my workarounds

For Swift Developers

Scott
2 min readJun 11, 2020
  1. It only automatically works for one type of formatted date. If the JSON provides a date with a non-default format, the codable protocol will fail. Solution: Let it be a string so Codable works, and then provide a computed property that converts it into a date.
  2. No property can be of a protocol type unless it is computed. This really sucks. Sometimes APIs like to receive JSON where one property can have different types of objects. No help here, from codable. You can create a custom decodable initializer and encode method, but then you have to provide unique keys for each conformance to the protocol, not only does this somewhat defeat some of the purpose of a protocol, which provides ease of use so long as your object conforms to the protocol, but it means your object will have different keys for these different objects if you serialize it to a dictionary. Wait, you say, if we change the CodingKey enum values, then we make it so we can retain the same property name with different objects conforming to the same protocol. But then enum raw values can’t be the same. Small Solution: let the property be a dictionary with a codable key and codable value types. You can create initializers and builders that accept the custom codable types that conform to your protocol, and then convert them into dictionaries and assign them to these pesky properties. If you have nested dictionaries in this property then you have to do some more work.

Most importantly

Use a json converting tool like app.quicktype.io

--

--