Get rid of that hefty code..!!!🤗 NSCoding As we are all aware, to support encoding and decoding of instances in iOS, a class must adopt the protocol and implement its methods: NSCoding — Returns an object initialized from data in a given unarchiver. init(coder:) — Encodes the receiver using a given archiver. encode(with:) Example: and must contain the code for each property that needs to be encoded or decoded. 😲 init(coder:) encode(with:) Well, it seems that you have to write so much of redundant code 😖 only with the property name changes. Copy Paste..Copy Paste..!!!😕😴 But why should I do that? 🙇♀️ If the property names are same as the key names and I don’t have any specific requirements, why don’t handle everything at its own end? 🤷♀️ Why do I have to write so much code? Noooooo..!!! 😼 NSCoding OMG..!!! Another problem 🤦♀️. It doesn’t even support . 👺 And that means I have to make a every-time I need to serialize the data, even if I don’t have any class-specific requirement. 🤒 structs and enums class Such a waste of time 🤢. Help me..!!!🙏 Well..well..well..Don’t worry. is here to your rescue again. 🤠 Apple What’s new in Swift 4? In its release, unveiled a brand new way of data encoding and decoding 🤓 by conforming your custom types with some easy to adopt protocols, Swift 4 Apple — for encoding Encodable — for decoding Decodable — for both encoding as well as decoding Codable It provides support for as well. 👌👌 class, struct and enum 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: Encodes this value into the given encoder. encode(to:) — 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: — Creates a new instance by decoding from the given decoder. init(from:) 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 as well as Encodable Decodable. You’ll learn more about and in the upcoming sections 👽. encode(to:) init(from:) 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 Built-in types — Codable String, Int, Double, Data, URL are if they contain types Array, Dictionary, Optional Codable Codable So, now that we have seen what is, let’s see how to actually use it to encode and decode our own custom types. Here we go..🙂 Codable Encoding — JSONEncoder You can use to convert your into . JSONEncoder codable type Data method returns a JSON-encoded representation of the . JSONEncoder’s encode(_:) codable type Whatttttt…!!! 😱 Just 1 line of code? That’s it? You’re kidding right? There must be something else..some catch..it can’t be..🤯 😂😎 yes this is the only code you need to write to get it working. Isn’t it awesome 👏?. Just 2 simple steps and you are done. No need for that hefty code anymore with so much of overhead. Hi5 ✋. Like encoding, you can easily get your hands on decoding as well. So what are you waiting for?🤓 Get on with it..🤗 JSONDecoder Decoding — Just like , there exist that can be used to decode your JSON data back into your . JSONEncoder JSONDecoder codable type method returns a value of the you specify, decoded from a JSON object. JSONDecoder’s decode(_:from:) codable type That’s it. That’s how you can encode/decode your Codable Type. Just 2 steps: Conform your custom type to Codable protocol. Use to encode/decode your custom object. JSONEncoder/JSONDecoder Choosing Properties to Encode and Decode — CodingKeys There might be some questions ❓❓coming to your mind, What if I want to omit some properties of the from the serialization process? Codable Type How to encode/decode if some of the keys 🔑 included in the serialized data doesn’t match the property names of the ? Codable Type Well, provided solution for that too — Apple enum CodingKeys. Codable types can declare a special nested enumeration named CodingKeys that conforms to the CodingKey protocol. When this enumeration is present, its cases serve as the authoritative list of properties that must be included when instances of a codable type are encoded or decoded. Things to note about CodingKeys: It has a and conform to protocol. Raw Type — String CodingKey The names of the enum cases should 💯 the property names of the . exactly match Codable Type ✅— Omit the properties from if you want to omit them from encoding/decoding process. A property omitted from needs a default value. Answer to 1st Question CodingKeys CodingKeys ✅ — is the thing you need if the property names of doesn’t match the keys in the serialized data. Provide alternative keys by specifying as the raw-value type for the enumeration. The string you use as a raw value for each enumeration case is the key name used during encoding and decoding. Answer to 2nd Question Raw Value Codable Type String CodingKeys Example: In the below code snippet, is omitted from the and hence is provided a default value. var format: String = “png” CodingKeys Properties and are renamed to and using the in and title url name link raw value CodingKeys — case title = “name” case url = “link” Encode and Decode Manually ✏️ There exist scenarios when the structure of your differs from the structure of its encoded form, : Codable Type for example When you encode a object using the above declaration, the you get looks something like: Photo Photo JSON What if you don’t want “ and “ nested in “ ? 🤔i.e. your should look something like: width” height” size” JSON In that case, you can provide your own custom logic 📝 of and to define your own encoding and decoding logic. Encodable Decodable You need to implement and methods of and protocols explicitly. encode(to:) init(from:) Encodable Decodable Follow the below steps: Update the to include and keys instead of . enum CodingKeys width height size Remove the conformance to from . Codable Photo Create a conforming to and implement method. Photo extension Encodable encode(to:) Create a conforming to and implement method. Photo extension Decodable init(from:) Limitations 🚫 For now you cannot conform to in an 🙅♀️. It might be available in further releases. Codable extension Too many yets in this release 🙈. I don’t know why is in so much hurry..🤔 Apple 2. You must use a to encode and decode. concrete type You can get a nice use-case of this scenario . here Promotions Don’t forget to read my other articles: Drag It & Drop It in Collection & Table — iOS 11 UITableView Leading & Trailing Swipe Actions in iOS 11 Swift 4.0 Migration — ERROR..!! ERROR..!! All you need to know about Today Extensions (Widget) in iOS 10 UICollectionViewCell selection made easy..!! Feel free to leave comments if you have any doubts. 🙂🙃
Share Your Thoughts