0Pricing
Swift Academy · Lesson

Manual encode(to:) and init(from:)

Take full control of serialization logic.

When Synthesis Is Not Enough

Sometimes the JSON shape does not line up with your properties — you need computed transforms, default fallbacks, or flattening. Then you implement encode(to:) and init(from:) by hand.

import Foundation

struct Temperature: Codable {
    var celsius: Double
}

print("Manual coding gives full control")

Declaring CodingKeys First

Manual coding starts with a CodingKeys enum. The keyed containers use these keys to read and write values.

import Foundation

struct User {
    var name: String
    var age: Int
    enum CodingKeys: String, CodingKey {
        case name
        case age
    }
}

print(User.CodingKeys.name.stringValue)

All lessons in this course

  1. CodingKeys for Renaming
  2. Key and Date Decoding Strategies
  3. Manual encode(to:) and init(from:)
  4. Decoding Heterogeneous JSON
← Back to Swift Academy