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
- CodingKeys for Renaming
- Key and Date Decoding Strategies
- Manual encode(to:) and init(from:)
- Decoding Heterogeneous JSON