6 Advanced Swift Codable tips
Lossy array, decoding strategies, parsing dynamic types, & more!
Model layer is the foundation of every app. One way to keep model layer clean is by being able to cleanly manipulate and transform Data or JSON string into Swift type and vice versa. On September 2017, Swift 4 came out with Codable
protocol that allows us to cleanly create standard mappings between transmission data format (JSON string, binary data, etc.) into storage data format (Swift types). We don’t need to parse them manually anymore. This made a huge difference.
In this article, I want to show you tips and tricks around using Codable
protocol that are not so obvious at first glance. I use these tips regularly in my daily work at Rakuten Viki.
I’ll use Xcode 11 and Swift 5.1 in this blog.
1. Skip array elements that fail to parse
When parsing an array, some element can get corrupted and makes parsing of the whole array fail. In some case, we still want to continue with the array holding those successfully parsed elements.
This drop-in Decodable
array wrapper called LossyArray
skips failed elements, retaining only successful ones. It uses decoder unkeyedContainer()
function to iterate through the elements. To use this, just pass…