Junior — Middle
Can you explain what the Codable protocol is and its main functions?
sobes.tech AI
Answer from AI
Codable is a protocol in Swift that combines the capabilities of encoding (Encodable) and decoding (Decodable) objects into various formats, such as JSON or Property List.
Main functions of Codable:
- Allows easy serialization of objects into data formats for storage or transmission.
- Enables deserialization of data back into objects.
- Simplifies working with external APIs and local storage.
Example of using Codable for JSON:
struct User: Codable {
let id: Int
let name: String
}
let jsonData = "{\"id\":1, \"name\":\"Ivan\"}".data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: jsonData)
print(user.name) // Ivan
Thus, Codable greatly simplifies data transformation between Swift objects and external formats.