Swift Academy · Lesson

Handling Optional and Nested Types

Decode optionals and nested structures safely.

Lesson 4 of 413 steps

Handling Optional and Nested Types is a free Swift Academy lesson on CoddyKit. This is lesson 4 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.

Optional Properties

An optional property is naturally Codable when its wrapped type is. A missing JSON key decodes to nil; a present one decodes normally.

import Foundation

struct User: Codable {
    var name: String
    var nickname: String?
}

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

Encoding nil Optionals

By default a nil optional is left out of the encoded JSON entirely, producing a smaller payload.

import Foundation

struct User: Codable {
    var name: String
    var nickname: String?
}

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

Explicit null Decodes to nil

If the JSON contains an explicit null for an optional property, it decodes to nil rather than throwing an error.

import Foundation

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

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

Nested Codable Structs

Compose models by nesting Codable types. The outer type encodes and decodes the inner one automatically.

import Foundation

struct Address: Codable { var city: String; var zip: String }
struct Person: Codable { var name: String; var address: Address }

let p = Person(name: "Lee", address: Address(city: "Rome", zip: "00100"))
let data = try JSONEncoder().encode(p)
print(String(data: data, encoding: .utf8)!)

Decoding Nested Structs

The reverse works too: nested JSON objects decode into the nested struct properties.

import Foundation

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

let json = "{\"name\":\"Lee\",\"address\":{\"city\":\"Rome\"}}"
let p = try JSONDecoder().decode(Person.self, from: json.data(using: .utf8)!)
print(p.address.city)

Optional Nested Types

A nested struct can itself be optional. If the key is absent, the whole nested value becomes nil.

import Foundation

struct Address: Codable { var city: String }
struct Person: Codable { var name: String; var address: Address? }

let json = "{\"name\":\"Lee\"}"
let p = try JSONDecoder().decode(Person.self, from: json.data(using: .utf8)!)
print(p.address?.city ?? "no address")

Arrays of Codable

An array of a Codable element type is itself Codable. It maps directly to a JSON array of objects.

import Foundation

struct Tag: Codable { var name: String }
struct Post: Codable { var title: String; var tags: [Tag] }

let p = Post(title: "Hi", tags: [Tag(name: "swift"), Tag(name: "json")])
let data = try JSONEncoder().encode(p)
print(String(data: data, encoding: .utf8)!)

Decoding Arrays of Structs

Decoding a JSON array of objects yields a Swift array of typed values you can iterate.

import Foundation

struct Tag: Codable { var name: String }

let json = "[{\"name\":\"a\"},{\"name\":\"b\"}]"
let tags = try JSONDecoder().decode([Tag].self, from: json.data(using: .utf8)!)
for t in tags { print(t.name) }

Optional Arrays

An optional array distinguishes "key absent" (nil) from "present but empty" ([]). Both are valid and meaningful states.

import Foundation

struct Box: Codable { var items: [String]? }

let a = try JSONDecoder().decode(Box.self, from: "{}".data(using: .utf8)!)
let b = try JSONDecoder().decode(Box.self, from: "{\"items\":[]}".data(using: .utf8)!)
print(a.items == nil, b.items == [])

Deeply Nested Structures

Nesting can go several levels deep — structs inside arrays inside structs. Codable handles each layer recursively.

import Foundation

struct Comment: Codable { var text: String }
struct Article: Codable { var title: String; var comments: [Comment] }
struct Feed: Codable { var articles: [Article] }

let feed = Feed(articles: [Article(title: "A", comments: [Comment(text: "hi")])])
let data = try JSONEncoder().encode(feed)
print(String(data: data, encoding: .utf8)!)

Round-Trip with Optionals and Nesting

Combining everything: optional fields, nested structs, and arrays survive a full encode/decode round-trip intact.

import Foundation

struct Address: Codable { var city: String }
struct Person: Codable {
    var name: String
    var address: Address?
    var hobbies: [String]
}

let p = Person(name: "Mo", address: Address(city: "Cairo"), hobbies: ["chess"])
let data = try JSONEncoder().encode(p)
let back = try JSONDecoder().decode(Person.self, from: data)
print(back.address?.city ?? "-", back.hobbies.first ?? "-")

Quick Check: Optionals and Nesting

Test your understanding of optional and nested Codable types.

Recap: Optional and Nested Types

You learned how Codable handles richer shapes:

  • Optional properties tolerate missing keys and explicit null, decoding to nil.
  • nil optionals are omitted when encoding by default.
  • Nested Codable structs and arrays encode/decode recursively.
  • Optional arrays distinguish absent (nil) from empty ([]).
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 “Handling Optional and Nested Types” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Handling Optional and Nested Types”, 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 “Handling Optional and Nested Types”?

Decode optionals and nested structures safely. 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 4 of 4.

How long does the “Handling Optional and Nested Types” 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