Use Codable Protocol in Swift
Written by Team Kodeco
Codable
is a protocol in Swift that allows objects to be encoded and decoded to and from external representations such as JSON, XML, or Plist data. By conforming to the Codable
protocol, objects can be easily converted to and from data, allowing them to be saved or sent over a network.
To conform to Codable
, an object needs to declare its properties and their data types, and the Swift compiler generates the necessary encoding and decoding methods automatically. By using Codable
, developers can save time and effort in writing custom encoding and decoding logic.
Here is an example using Codable
in Swift:
import Foundation
struct Person: Codable {
let firstName: String
let lastName: String
let age: Int
}
let person = Person(firstName: "John", lastName: "Doe", age: 30)
// Encoding to JSON
let encoder = JSONEncoder()
let data = try encoder.encode(person)
// Decoding from JSON
let decoder = JSONDecoder()
let decodedPerson = try decoder.decode(Person.self, from: data)
print(decodedPerson)
// Output: Person(firstName: "John", lastName: "Doe", age: 30)
In this example, the Person
struct conforms to Codable
protocol allowing you to easily encode the Person
instance to JSON using JSONEncoder
and decode it back to a Person
instance using JSONDecoder
.