doyeona
Published in

doyeona

Codable = Decodable + Encodable

What is Codable? Codable is to convert the JSON data object to an actual Swift class or struct and vice versa.

It’s usually used when the case you wanna retrieve or parse JSON data from the server like the APIs.

JSON is an open standard file format, and data interchange format, that uses human-readable to store and transmit data objects consisting of attribute-value pairs and array data types. 👉🏻 more explanation about it will be later

Codable was introduced in Swift 4 so before then, Swift coders used different ways to parse the JSON data from the server using NSCoding. Let’s first study about the basic info about NSCoding.

NSCoding

It is a protocol that a class must adopt the NSCoding protocol and implement its required methods in order for us to decode and encode JSON data.

  • encode(with:) instructs the object to encode its instance variables to the code provided.
  • init(coder:) instructs the object to initialize itself from data in the coder provided.
func encode(with aCoder: NSCoder) {
//add code here
}

required convenience init?(coder aDecoder: NSCoder) {
//add code here
self.init(title: "", rating: 0)
}
  • Still best way of using in inherited classes
  • Be aware of using it with NSObject
  • Code redundancy
  • Doesn’t support structs and enums
  • Depends on Foundation

So it means every time when you wanna parse the data, you should always make class and implement two methods that are needed in order for you to encode or decode the data.

If you want to query or create complex object graphs, then you should use Core Data, Realm or another database solution instead.

To avoid those problems and just parse the data as simply as possible, use Codable.

Codable

Codable is a type alias for the Encodable and Decodable protocols.

  • It doesn’t depends on any frameworks
  • need to write models in Swift
typealias Codable = Decodable & Encodable
  • Decodable protocol Decodable : A type that can decode itself from an external representation (bytes to object)
  • Encodable protocol Encodable : A type that can encode itself to an external representation. (object to bytes)
  • Codable = both encoding and decoding

Encode and Decode Automatically

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

Types: String, Int, Double, Date, Data

Also, Array, Dictionary and Optional conform to Codable whenever they contain Codable types.

Adding Codable to the inheritance list for Response and Track triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable.

but what if they give they return “results” and i want to name it into tracks instead?

CodingKeys

then we conform the protocol CodingKeys to rename the key/variable as we want as below. CodingKey is A type that can be used as a key for encoding and decoding.

To summarized it,

1️⃣ we need to use Codable to convert the data into Object(structure) from the server and visa versa because if we don’t we’ll be only seeing bytes!

2️⃣ Before Swift 4, NSCoding is mostly used and it’s still better to use with complexity of inherited classes and not possible to use it with structure

3️⃣ Use CodingKeys to change the variable’s name that we got from the server into our own taste 😋

Therefore… This is all required for us to communicate with the server isn’t it? To get the data (API) and to send the data?

YES! Then let’s study basic JSON. If we can get the data from the server into bytes and successfully convert the data to our own object using Codable, then why do we need to know about JSON? Why do people talk about it? and Why most of the file formats are in JSON?

JSON

JSON is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute value pairs and array data types.

So we can still get the data from the server but to communicate with other developers, we need to know the format that we are receiving. What if all the developers have their own unique format of file? then we have to ask each of them about the file format, in order for us to fetch the data. Isn’t it too hassle?

That’s why we have the common file format to easily communicate with other developers or fetch the data! and that mostly used format is called JSON because it is more readable with less size. (also there’s another famous file format mostly used before called XML)

Anyway that’s the reason why we mostly use JSON format to communicate with the server and convert the data that is in bytes to our own object using Codable and that’s what we called deserialization and the opposite is called serialization.

Why do we need Serialization? -> click this link to read more! , I think I need to make a separate article about serialization after I study more about it.

Anyway .. ! LET’S MOVE ON DOYEON!

Encode the data (Object -> Byte(String)), Serialization

1️⃣ Let’s make the values with above structure that we created inside the function or anywhere is 👌🏻

2️⃣ Encode the object!

let encodeData = try? JSONEncoder().encode(trackObject)

3️⃣ print the encodeData then you will see the data encoded successfully with bytes.

print(encodeData) // Optional(227 bytes)

btw, let’s look intoJSONEncoder().encode If you wanna know why it returns byte…. well… 👇🏻

https://developer.apple.com/documentation/foundation/jsonencoder

Okay so it simply encodes instances of data to JSON objects. Then what about .encode ?

Well.. I’m guessing it will encode the data to Base64 String? because i see lots of “base64String” and as i understanding, it should be..

If anyone knows exactly how it works, please let me know 🙏🏻

Decode the data (Bytes(String) -> Object), Deserialization

So when you are able to encode the data, let’s decode the data that we encoded.

I made another method called “decodeData ‘’ inside the encodeData method and passed the encoded Data to decodedData method. Somewhat like this: decodeData(decodeData: encodeData!) (do your own safe unwrapping ❗️)

1️⃣ Make another method called decodeDate which accepts encoded object

func decodeData(decodeData: Data) {
//
}

2️⃣ Let’s try to check our data in text or String. So what we are doing is converting the data to String so that we can see it!

func decodeData(decodeData: Data) {
let resultString = String(data: decodeData, encoding: .utf8)
print("Data in String: \(resultString)")
}

3️⃣ If you see text in the console like below,

When we see those texts above, delete those above stuff and Let’s decode it into our Response struct . Like storing it into our own created structure format(Response) by typing a couple of these lines.

let decoder = JSONDecoder()
let response = try decoder.decode(Response.self, from: decodeData)

Then we’ll see the above texts are already in our response with the type of Response struct that we created.

So with these steps, you can now retrieve the data from the server and send the data in JSON format but be sure to use do catch statement for Error Handling.

See the completed code for this[.palyground]:

This article is all about Codable (decode, encode), not fetching data from the server but this is how it works basically i guess. If you are trying to fetch some data from the server(API) then try to look for URL session. I wanted to continue writing about fetching data from the server (itunes) but this post gets too long and i’m bit tired looking at the same post for several days! Maybe i will continue writing it later.

Thank you for reading this post and hopefully this might help you understand Codable and the basic concept of using JSON. What i wrote might not be 100% correct because i also do research and study for myself, but i tried my best to understand it(and i’m still a beginner 😂)! So please Please if there’s anything i need to know or update, feel free to message me! Let’s study and share our knowledge together 💜

references:

Serialization

--

--

--

Daily study logs about iOS development will be updated. Any recommendations or discussions are always welcome

Recommended from Medium

RxJava: FlatMap, SwitchMap and ConcatMap differences & examples

P2 Development Plans

Exploring the game development world: Unexpected plot twist

5 Reasons why should you Hire Dedicated PHP Developer

Monitor your app reviews; Using Slack and Firebase — For free.

Customer Profile with Django Signal — Django101

Various toughts on rendering/computer graphics and attitude towards programming

Podcast S2E8: Community Learning

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Doyeon

Doyeon

Hey! I am currently studying iOS by myself, and wanna be a cool app developer 🕶 please correct me if i’m wrong or if there’s any thing that you wanna share😊✌️

More from Medium

Initializers in Swift — Part 1/3 (Structures and enumerations)

How To Use UIView as NavigationBar Which Allow You to change NavigationBar Size

BigNav

What is a Lazy Stored Property and when to use it?

Property Observers in Swift 5