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.
Codable
:
Codable
is a Swift protocol that combines Encodable
and Decodable
protocols.Codable
, it means that instances of that type can be both encoded (converted to a serializable format) and decoded (converted from a serializable format) using the Codable APIs.Codable
, you get both encoding and decoding functionality for free, and you can use it to easily serialize and deserialize your data to and from various formats.Example:
struct MyStruct: Codable {
let name: String
let age: Int
}
Decodable
:
Decodable
is a Swift protocol that is part of the Codable framework.Decodable
, it means that instances of that type can be decoded from a serializable format, but they cannot be encoded to that format using the Codable APIs.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.
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)")
}
}