Monthly Archives:juin 2017

Codable protocol in Swift 4 + extension

Juin 14, 17
Frédéric ADDA
,
No Comments

When Swift 4 went out and we finally had a chance to play with it in a playground, I began reading this article on Ray Wenderlich’s site :

https://www.raywenderlich.com/163857/whats-new-swift-4

 

I was particularly interested in this part about the new Codable protocol :

As you can see, it’s a pretty interesting (and simple) way to convert a Codable into a String (a stringified version of a JSON dictionary).

 

I also read this article from Natasha-The-Robot’s weekly newsletter : https://cur.at/hxKamEa?m=email&sid=QSej7qn

This is interesting: the author creates a new protocol (Serializable) to let the Codable-conforming object encode itself to Data.

 

Well, as far as I’m concerned, I often have to parse a JSON dictionary (a.k.a. a Dictionary<String, Any>), or create a JSON dictionary from an object, not a String or a Data.

So, this is my implementation of this Serializable protocol idea :

 

The JSONCodable protocol now has two required methods :

  • a function allowing the Serializable-conforming object to convert itself a JSON dictionary
  • an initializer allowing us to initialize a new object by parsing a JSON dictionary.

If you often have to work with web services (as I do), this is handy.