A Swift app's weather API wraps each forecast in a "data" envelope with snake_case fields; how do you decode it into a flat struct with a custom init(from:)?
answer
- containers are typed views
- one key enum per level
- nestedContainer for the envelope
- decodeIfPresent plus a fallback
- encoding is not mirrored for free
basics
~20 sIn init(from:), open the root container with a RootKeys enum, call nestedContainer(keyedBy:forKey: .data) with a second key enum, and decode each field there, using decodeIfPresent with ?? for optional fields. Write a matching encode(to:) or the encoder writes a flat object.
solid answer
~40 sDeclare two `CodingKey` enums, `RootKeys` with `data` and `DataKeys` with raw values such as `city = "city_name"`. In `init(from:)`, call `decoder.container(keyedBy: RootKeys.self)`, then `nestedContainer(keyedBy: DataKeys.self, forKey: .data)`, and assign every property from that inner container: `decode(_:forKey:)` for required fields, `decodeIfPresent(_:forKey:) ?? []` where the server may omit a value. Errors keep their coding path, so a missing `temp_c` reports path `data`. Writing `init(from:)` does not change encoding: if the type declares `Codable`, the compiler still synthesizes `encode(to:)` from property names and writes a flat object, so write `encode(to:)` with nested containers or declare only `Decodable`. When the inner object fits synthesis, a generic `Envelope<Payload: Decodable>` with `let data: Payload` is simpler.
code
swift · 30 linesimport Foundation
struct Forecast: Codable {
let city: String
let tempC: Double
let alerts: [String]
enum RootKeys: String, CodingKey { case data }
enum DataKeys: String, CodingKey {
case city = "city_name"
case tempC = "temp_c"
case alerts
}
init(from decoder: any Decoder) throws {
let root = try decoder.container(keyedBy: RootKeys.self)
let data = try root.nestedContainer(keyedBy: DataKeys.self, forKey: .data)
city = try data.decode(String.self, forKey: .city)
tempC = try data.decode(Double.self, forKey: .tempC)
alerts = try data.decodeIfPresent([String].self, forKey: .alerts) ?? []
}
func encode(to encoder: any Encoder) throws {
var root = encoder.container(keyedBy: RootKeys.self)
var data = root.nestedContainer(keyedBy: DataKeys.self, forKey: .data)
try data.encode(city, forKey: .city)
try data.encode(tempC, forKey: .tempC)
try data.encode(alerts, forKey: .alerts)
}
}go deeper
Recall that a custom init(from:) opens a container with a CodingKey enum and decodes each property by key.
Explain nestedContainer(keyedBy:forKey:), decode versus decodeIfPresent, and why every stored property must be assigned in the custom initializer.
Check the asymmetric case in review: a custom decoder with a synthesized encoder writes a different shape, so ask for encode(to:) or a Decodable-only conformance and a round-trip test.
Choose between per-type custom decoding and a shared generic envelope for the whole API, weighing boilerplate against how many endpoints share the wrapper.
## The shape problem A weather API returns: ```json {"data": {"city_name": "Oslo", "temp_c": 3.5, "alerts": ["wind"]}} ``` The app wants a flat `Forecast` with `city`, `tempC` and `alerts`, and `alerts` may be missing on calm days. Synthesized `Codable` maps one JSON object to one Swift type, so it cannot skip the `data` level or supply a fallback for a missing key. A hand-written **`init(from:)`** can do both. ## The container API Inside `init(from decoder: any Decoder)` you ask the decoder for **containers**, typed views over the JSON: - `decoder.container(keyedBy:)` returns a `KeyedDecodingContainer` for a JSON object, keyed by a `CodingKey` enum you choose; - `nestedContainer(keyedBy:forKey:)` on that container returns a keyed view of the object stored under one key, here `data`, with its own key enum; - `nestedUnkeyedContainer(forKey:)` does the same for a JSON array; - `decoder.singleValueContainer()` is for a value that is not an object, such as a string-backed enum. Key enums do not have to be called `CodingKeys`; any `enum ...: String, CodingKey` works, and naming them `RootKeys` and `DataKeys` makes the two levels obvious. ## Decoding with fallbacks Within the nested container, choose per field: | Call | Key missing | `null` | Wrong type | |---|---|---|---| | `decode(_:forKey:)` | throws `keyNotFound` | throws `valueNotFound` | throws `typeMismatch` | | `decodeIfPresent(_:forKey:)` | `nil` | `nil` | throws `typeMismatch` | | `contains(_:)` | `false` | `true` | `true` | `try data.decodeIfPresent([String].self, forKey: .alerts) ?? []` turns "absent or null" into an empty array while still rejecting a value of the wrong type. When "absent" and "explicitly null" must mean different things, test `contains(_:)` first, as the standard library's doc comment for `decodeIfPresent` suggests. ## What you take on by writing `init(from:)` 1. **You own every property.** The synthesized initializer is gone, so each stored property must be assigned on every path, exactly as in any other initializer. 2. **Errors keep their paths.** A missing `temp_c` throws `keyNotFound` with the coding path `data`, and a `data` that is an array throws `typeMismatch` at `data`, because nested containers extend the path automatically. 3. **Encoding is a separate requirement.** If the type declares `Codable` and you write only `init(from:)`, the compiler still synthesizes `encode(to:)` from a synthesized `CodingKeys` built from the property names. Your `RootKeys` and `DataKeys` are not used, so the encoder writes a flat `{"city": ..., "tempC": ..., "alerts": ...}` that your own decoder cannot read back. Write `encode(to:)` with `nestedContainer(keyedBy:forKey:)` on the encoder's container, or declare only `Decodable`. ## Encoding the envelope back The encoding side uses the same shape of API with mutable containers. `encoder.container(keyedBy:)` returns a `KeyedEncodingContainer` that you hold in a `var`, and its `nestedContainer(keyedBy:forKey:)` is a mutating method that returns another `var` container for the `data` object. Each `encode(_:forKey:)` writes one value; `encodeIfPresent(_:forKey:)` omits the key when the value is `nil`, which matches what the synthesized encoder does for optionals. Writing both directions by hand is more code, but it keeps the type's encoded form identical to what it decodes, which is what a cache or an upload expects. ## A lighter alternative: a generic envelope When the inner object already fits synthesis, decode the wrapper instead of hand-writing anything: ```swift struct Envelope<Payload: Decodable>: Decodable { let data: Payload } let forecast = try decoder.decode(Envelope<Forecast>.self, from: json).data ``` Here `Forecast` uses plain synthesized `Decodable`, perhaps with `.convertFromSnakeCase` on the decoder, and one generic type absorbs every endpoint that uses the same envelope. Prefer this when the only mismatch is the wrapper; reach for a custom `init(from:)` when fields need fallbacks, flattening from several levels, or validation. ## Review checklist - Does every `decodeIfPresent` fallback reflect a real server contract, or does it hide a bug? - Is `encode(to:)` written, or the conformance narrowed to `Decodable`? - Is there a test that decodes a recorded payload and, if encoding matters, round-trips it?
- How do you tell an absent `alerts` key from an explicit `"alerts": null`?`decodeIfPresent` returns `nil` for both. Call `data.contains(.alerts)` first: it is `false` only when the key is absent, so you can treat an explicit `null` differently, for example as a server instruction to clear cached alerts.
- What does `JSONEncoder` write for this type if you delete `encode(to:)` but keep the `Codable` declaration?The compiler synthesizes `encode(to:)` with a synthesized `CodingKeys` built from the property names, ignoring `RootKeys` and `DataKeys`. The output is a flat object such as `{"city": "Oslo", "tempC": 3.5, "alerts": []}`, which the custom decoder rejects because it has no `data` key.
- Synthesized Codable can skip a wrapper level if CodingKeys is nested.
- Writing init(from:) also makes the synthesized encode(to:) use the same keys.
- decodeIfPresent with ?? also recovers from a value of the wrong type.
- Key enums used in a custom init(from:) must be named CodingKeys.
- Errors from a nested container lose the path to the envelope.