Encoding and Decoding in Swift 4
I know I know I know you must be like Swift 4 WTF! Don’t worry Swift 4 is not out yet but you can still play around with Swift 4 features using the Swift Development Snapshot.
If you are interested in installing Swift 4 snapshot then check out this link.
There are many different scenarios, where you want to convert your class to Data representation. A very common need is when you want to POST JSON data as a HTTP body. One of the most common approaches is shown below:
The JSONSerialization class is responsible for returning a Data object, which can then be passed as an HTTPBody to a request.
JSONEncoder and JSONDecoder in Swift 4
Swift 4 introduces JSONEncoder and JSONDecoder classes which can easily convert an object to encoded JSON representation. Check out the example below:
Notice the use of the new Codable protocol, which makes the Language structure encodable and decodable. Later JSONEncoder class is used to perform the encoding by using the encode function.
Just like encoding, decoding is also very simple as indicated in the code below:
Pretty simple right! We can even make it more simpler through the use of protocols and extensions. Let’s create a custom Serializable protocol which will perform the encoding for us.
Using JSONEncoder and JSONDecoder is fine but we can certainly make it more seamless to perform encodings and decodings. Instead of creating an instance of JSONEncoder a class or struct should be able to encode themselves. Take a look at the Serializable protocol below which can be conformed by all models who are interested in being encoded.
Instead of implementing the serialize function separately in each class or struct we will use the power of protocol extensions to create a default implementation.
The above code will give you the following error:
Playground execution failed: error: MyPlayground.playground:8:36: error: argument type ‘Self’ does not conform to expected type ‘Encodable’return try? encoder.encode(self)
The problem is that “self” is not Codable. We can easily fix this by conforming the Serializable protocol to the Codable protocol as shown below:
Now, you can easily encode your models using the new Serializable protocol as shown below:
Make sure your Language model conforms to the “Serializable” protocol and not “Codable” protocol.
I believe these new advancements in Swift 4 will really benefit developers when building applications that rely on networking services and posting encoded data.
I am available to work as a senior iOS developer. If you are interested then check out my resume here.
If you like this post then you might be interested in checking out my course “A Complete Guide to Lean Controllers in iOS”. The course covers many useful architecture patterns to build better iOS applications. Receive a 74% discount, click on the following link: