Swift – NSCoder | Codable | JSONDecoder | JSONEncoder | NSKeyedArchiver | NSKeyedUnarchiver | Serialize | Deserialize | Marshelling | Demarshelling | Parse JSON | Parse Plist

Source code :

CodableExample.playground 2

Codable and

NSKeyedArchiverBlog-master

We can persist data by using NSCoder or Codable protocols and use NSKeyedArchiver to persist/save and NSKeyedUnarchiver to fetch data to and from user document directory respectively.

Note: We have NSCoder (support still available for swift (but Codable the new introduced protocol in swift 4.0 better suits), we can useNSCoder protocol in objective c and pre swift 4.0 ) and Codable (latest protocol introduced by apple in swift 4.0, will work only with projects supporting swift 4, Does not support objective c at all) protocols to achieve decoding and encoding.

 

When you’ll need to save data to a file or to send it over the network. Converting your instances to another representation, like a string or a stream of bytes. This process is known as encoding, also known as serialization.

The reverse process of turning the data into an instance is called decoding, or deserialization.

Imagine you have an instance(array/dictionary/class/struct) you want to write to a file. The instance itself cannot be written as-is to the file, so you need to encode it into another representation, like as a stream of bytes:

Once the data is encoded and saved to a file, you can turn it back into an instance whenever you want by using a decoder:

To support encoding and decoding of instances in iOS, a class must adopt the NSCoding protocol and implement its methods:

  1. init(coder:)— Returns an object initialized from data(bytes/raws) in a given unarchiver.
  2. encode(with:)—Archive data.

Problems:

  1. To support Decode and Encode using NSCoder, your class must inherit from NSObject and confirm NSCoding Protocol. WHYYY!! Then WHAT ABOUT STRUCTS (THAT”S WHY APPLE INTRODUCES CODABLE).
  2. No Error handling with NSCoding available.

Encodable & Decodable, combined Codable to solve above problems from swift 4, xcode 9, iOS11. 

 If you haven’t seen it already, I suggest you to watch the related WWDC session(the Codablepart starts past 23 minutes).

  1. Swift 4 has introduced amazing Codableprotocol as part of Foundation framework .
  2. JSON parsing and plist parsing became a single or couple of lines of code, AND YOU GET YOUR MODEL DATA (supports both class and struct).
  3. We also get error handing with do try catch block (not available with NSCoder).
  4. Use JSONEncode and JSONDecode for json response encoding and decoding.
  5. Use PropertyListEncode and PropertyListDecode for property list encoding and decoding.
  6. It even supports Archive and unarchive data.

Apple unveiled a brand new way of data encoding and decoding 🤓 by conforming your custom types with some easy to adopt protocols,

  1. Encodable — for encoding
  2. Decodable — for decoding
  3. Codable — for both encoding as well as decoding

Codable provides support for class, struct and enum as well. 👌👌

So, let’s see what’s in it for us.

Encodable Protocol

A type that can encode itself to an external representation. It is used by the types that can be encoded.

It contains a single method:

encode(to:)Encodes this value into the given encoder.

Decodable Protocol

A type that can decode itself from an external representation. It is used by the types that can be decoded.

It also contains a single method:

init(from:) — Creates a new instance by decoding from the given decoder.

Codable Protocol

A type that can convert itself into and out of an external representation. It is used by the type can be both encoded as well as decoded.

typealias Codable = Decodable & Encodable

It includes the methods declared in both Encodable as well as Decodable.

You’ll learn more about encode(to:) and init(from:) in the upcoming sections 👽.

Codable Type

To encode and decode a custom type, we need to make it Codable.

The simplest way to make a type codable is to declare its properties using types that are already Codable.

  1. Built-in Codabletypes —String, Int, Double, Data, URL
  2. Array, Dictionary, Optionalare Codable if they contain Codable

Simple and couple of line of code only for Decoding, Encoding:

Let’s try to see how we can Parse, archive and unarchive using Codable:

Some more examples of parsing a JSON:

Yet another example:

Here is the source code:

CodableExample.playground 2

I have also attached below a source code i swift which used Codable to parse a plist.

The most important part of the project is

This class reads plist and decode the plist to array of

It uses

classes for decoding and encoding respectfully.

Here is the source code:

Codable