0Pricing
Swift Academy · Lesson

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

  1. Conforming to Codable
  2. Encoding with JSONEncoder
  3. Decoding with JSONDecoder
  4. Handling Optional and Nested Types
← Back to Swift Academy