Conforming to Codable
Make types encodable and decodable automatically.
What Is Codable?
Codable is a type alias for Encodable & Decodable. When a type conforms to it, Swift can turn instances into external data (like JSON) and rebuild them again — no manual parsing code required.
import Foundation
struct Book: Codable {
var title: String
var pages: Int
}
print("Book conforms to Codable")Automatic Synthesis
If every stored property is itself Codable, the compiler synthesizes the encoding and decoding logic for you. You only write the property list — Swift fills in the rest.
import Foundation
struct User: Codable {
var name: String
var age: Int
var isActive: Bool
}
let u = User(name: "Ada", age: 36, isActive: true)
print(u)All lessons in this course
- Conforming to Codable
- Encoding with JSONEncoder
- Decoding with JSONDecoder
- Handling Optional and Nested Types