Swift Academy · Lesson

Conforming to Codable

Make types encodable and decodable automatically.

Lesson 1 of 413 steps

Conforming to Codable is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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)

Encoding to JSON Data

A Codable value can be handed to a JSONEncoder, which produces a Data blob. Convert that Data to a String to inspect the JSON text.

import Foundation

struct User: Codable {
    var name: String
    var age: Int
}

let u = User(name: "Ada", age: 36)
let data = try JSONEncoder().encode(u)
print(String(data: data, encoding: .utf8)!)

Decoding from JSON Data

The reverse trip uses JSONDecoder. Give it the target type and the raw Data, and it reconstructs a fully typed Swift value.

import Foundation

struct User: Codable {
    var name: String
    var age: Int
}

let json = "{\"name\":\"Ada\",\"age\":36}"
let data = json.data(using: .utf8)!
let u = try JSONDecoder().decode(User.self, from: data)
print(u.name, u.age)

Round-Tripping a Value

Encoding then decoding should give back an equal value. This round-trip is a quick way to confirm a type's Codable conformance behaves as expected.

import Foundation

struct Point: Codable {
    var x: Int
    var y: Int
}

let p = Point(x: 3, y: 7)
let data = try JSONEncoder().encode(p)
let back = try JSONDecoder().decode(Point.self, from: data)
print(back.x, back.y)

Encodable Only

You can conform to just one half. Encodable means a type can be written out but not read back — handy for response models you never need to parse.

import Foundation

struct Receipt: Encodable {
    var item: String
    var total: Double
}

let r = Receipt(item: "Coffee", total: 4.5)
let data = try JSONEncoder().encode(r)
print(String(data: data, encoding: .utf8)!)

Decodable Only

Likewise, Decodable lets a type be built from external data without being encodable. Useful for read-only API payloads you only consume.

import Foundation

struct Config: Decodable {
    var version: Int
    var debug: Bool
}

let json = "{\"version\":2,\"debug\":true}"
let data = json.data(using: .utf8)!
let c = try JSONDecoder().decode(Config.self, from: data)
print(c.version, c.debug)

Supported Property Types

Standard library types like String, Int, Double, Bool, Date, Data, URL, plus arrays and dictionaries of Codable elements, are all Codable out of the box.

import Foundation

struct Profile: Codable {
    var name: String
    var tags: [String]
    var scores: [String: Int]
}

let p = Profile(name: "Sam", tags: ["a", "b"], scores: ["math": 90])
let data = try JSONEncoder().encode(p)
print(String(data: data, encoding: .utf8)!)

Enums Can Conform Too

An enum with raw values (like String or Int) becomes Codable automatically. It encodes as its raw value in the JSON.

import Foundation

enum Status: String, Codable {
    case active, paused, done
}

struct Task: Codable {
    var title: String
    var status: Status
}

let t = Task(title: "Ship", status: .active)
let data = try JSONEncoder().encode(t)
print(String(data: data, encoding: .utf8)!)

A Property Must Be Codable

Synthesis only works when all stored properties are Codable. If a custom type is used as a property, that type must also conform — otherwise the compiler refuses to synthesize.

import Foundation

struct Address: Codable {
    var city: String
}

struct Person: Codable {
    var name: String
    var address: Address
}

let p = Person(name: "Lee", address: Address(city: "Rome"))
print(try JSONEncoder().encode(p).count, "bytes")

Why Codable Matters

Codable removes hand-written serialization boilerplate, keeps the type as the single source of truth, and catches mismatches at compile time. It is the standard way to move data in and out of Swift apps.

import Foundation

struct Settings: Codable {
    var theme: String
    var fontSize: Int
}

let s = Settings(theme: "dark", fontSize: 14)
let data = try JSONEncoder().encode(s)
let back = try JSONDecoder().decode(Settings.self, from: data)
print(back.theme, back.fontSize)

Quick Check: Conforming to Codable

Test what you learned about conformance.

Recap: Conforming to Codable

You learned the foundation of serialization in Swift:

  • Codable = Encodable & Decodable.
  • Conformance is synthesized when all properties are Codable.
  • JSONEncoder produces Data; JSONDecoder rebuilds the value.
  • Standard types, raw-value enums, and nested Codable types are all supported.
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Conforming to Codable” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Conforming to Codable”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Conforming to Codable”?

Make types encodable and decodable automatically. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Conforming to Codable” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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