0Pricing
Swift Academy · Lesson

Conforming to Codable

Make types encodable and decodable automatically.

Conforming to Codable is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Conforming to Codable” lesson free?

Yes — the full text of “Conforming to Codable” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

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