What is the difference between the Codable and Decodable for a struct model?

In Swift, Codable and Decodable are related protocols that are used for encoding and decoding data to and from various formats, such as JSON, property lists, or other serialization formats. They are typically used with structs or classes to make them serializable.

  1. Codable:

Example:

struct MyStruct: Codable {
    let name: String
    let age: Int
}
  1. Decodable:

Example:

struct MyStruct: Decodable {
    let name: String
    let age: Int
}

In summary, if you want to both encode and decode your struct or class, you should conform to Codable. If you only need to decode data, then conforming to Decodable is sufficient. Conforming to Encodable alone is not very common because it typically makes sense to have both encoding and decoding capabilities when working with data serialization.


Explained with example

Sure! Let's illustrate the difference between Codable and Decodable with examples.

  1. Codable Example:

Suppose you have a struct called Person that you want to encode (serialize) to JSON and decode (deserialize) from JSON:

struct Person: Codable {
    let name: String
    let age: Int
}

let person = Person(name: "Alice", age: 30)

// Encoding (converting to JSON)
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(person) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print("Encoded JSON: \\\\(jsonString)")
    }
}

// Decoding (converting from JSON)
let json = """
{
    "name": "Bob",
    "age": 25
}
"""

if let jsonData = json.data(using: .utf8) {
    let decoder = JSONDecoder()
    if let decodedPerson = try? decoder.decode(Person.self, from: jsonData) {
        print("Decoded Person: \\\\(decodedPerson.name), \\\\(decodedPerson.age)")
    }
}