What is the difference between Codable and Decodable

Asked

Viewed 403 times

0

I’m kind of torn between Codable and Decodable on Swift. In which situations I should use codable and decodable.

I’m a beginner on Swift and the articles I found didn’t help me as much

Thanks in advance!

  • 1

    It’s basically their serialization.

  • @Maniero but the question is in which situations I should use codable or decodable sack?

1 answer

3


The Decodable protocol is implemented to define the decoding (deserialization) of the object from an external representation such as JSON, XML or Plist. Encodable is exactly the opposite, where it is defined as encoding (serializing) the object. When the type implements Codable it means that this has the two capabilities described above.

I created a playground to illustrate the difference.

The guy User implements Decodable, which allows creating instances from a JSON object.

Book implements Encodable, so that objects of this type can be serialized, generating an object of the type Date.

Finally, Job implements Codable. In the example, I coded and then decoded an object of this type.

import Foundation

struct User: Decodable {
    var name: String
    var age: Int
}

let rawData = """
{
    "name": "Rafael",
    "age": 99
}
""".data(using: .utf8)!

let user = try JSONDecoder().decode(User.self, from: rawData)
print(user.name)
print(user.age)

struct Book: Encodable {
    var id: Int
    var title: String
    var available: Bool
}

let book = Book(id: 10, title: "Swift", available: true)
let encodedBook = try JSONEncoder().encode(book)
let JSONString = String(data: encodedBook, encoding: String.Encoding.utf8)
print(JSONString!)

struct Job: Codable, Equatable {
    var title: String
    var salary: Float
}

let job = Job(title: "iOS Engineer", salary: 20000)
let encodedJob = try JSONEncoder().encode(job)
let decodedJob = try JSONDecoder().decode(Job.self, from: encodedJob)
print(job == decodedJob)

This example is quite simplistic, because the keys in JSON have exactly the same name as the attributes of the object. If it is necessary to (de)encode the object with different keys, just define Enum Codingkeys with the mapping between keys and attributes

enum CodingKeys: String, CodingKey { ...
  • Thank you very much, now I understand!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.