0Pricing
Swift Academy · Lesson

Handling Optional and Nested Types

Decode optionals and nested structures safely.

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)!)

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