Overblog
Edit post Follow this blog Administration + Create my blog

Codable/Decodable Improvemnts in Swift 4.1

May 10 2019


Codable/Decodable Improvemnts in Swift 4.1

In this post I’ll show you how to use custom keyDecodingStrategy/keyEncodingStrategy in new Codable/Decodable protocols in Swift 4.1 with a simple example.

In Swift 4.0 we had to create a custom CodingKeys enumeration to translate between snake_case, camelCase & custom representations of the properties about which you can read further here.

But in Swift 4.1 there’s a new keyDecodingStrategy property on JSONDecoder that can automatically map between snake_case and camelCase. While for these two you just have to assign and decoder will do the rest of the work for you. I’ll show you how to implement the custom key+decoding/encoding strategy to map the keys in the following gist.

During decoding, the closure is called once for each key in the Decodable value being decoded. The closure(.custom) is called along with an array of CodingKey instances representing the sequence of keys needed to reach the value being decoded.

Swift 4.1 is still in beta, so if you want to tinker around , you’ll have to download Xcode 9.3 beta.

Next in Codable/Decodable

I hope this post gives you an idea about Codable/Decodeble key parsing techniques. I’ll write about the same by taking more complex cases. Thanks.

Share this post
Repost0
To be informed of the latest articles, subscribe:
Comment on this post