skip to content

Codable and Serialization

Codable synthesizes encoding and decoding, and CodingKeys or a custom init(from:) handle mismatched shapes. Take-home apps parse an API, so interviewers probe decoding failures.

on this pageshow

explore

questions

6

In Swift, what does declaring Codable on a struct give you, and what must its stored properties satisfy to decode a flat JSON object?

level: juniorimportance: must knowfreq 80%

answer

  1. a typealias of two protocols
  2. compiler writes the keys enum
  3. every stored property must conform
  4. Optional decodes with decodeIfPresent

basics

~20 s

Codable (Encodable & Decodable) makes the compiler generate a CodingKeys enum, init(from:) and encode(to:) when every stored property's type conforms. Non-optional keys must be present; an Optional property decodes as nil when its key is missing or null.

solid answer

~50 s

`Codable` is a typealias for `Encodable & Decodable`. Declared on a struct in its own file, it makes the compiler synthesize a nested `CodingKeys` enum with one case per stored property, plus `init(from:)` and `encode(to:)`. That works only if every stored property's type conforms itself; `String`, numbers, `Bool`, `Date`, `URL` and collections of conforming types do. With `JSONDecoder` at its defaults, keys must match property names exactly. A missing key for a non-optional property throws `DecodingError.keyNotFound`, a `null` throws `valueNotFound`, a wrong JSON type throws `typeMismatch`. An `Optional` property is read with `decodeIfPresent`, so a missing key or `null` gives `nil`, but a wrong type still throws. Two traps: a `var` with a default value is still required by the synthesized initializer, and a `let` with an initial value is never decoded, with a compiler warning.

code

swift · 16 lines
swift
import Foundation

struct Weather: Codable {
    let city: String
    let tempC: Double
    var humidity: Int?            // missing key or null -> nil
    var units: String = "metric"  // still required by init(from:)
}

let json = #"{"city": "Oslo", "tempC": 3.5}"#
do {
    let weather = try JSONDecoder().decode(Weather.self, from: Data(json.utf8))
    print(weather)
} catch {
    print(error)  // keyNotFound for "units"
}

go deeper

for a junior

Recall that Codable is Encodable plus Decodable, that the compiler writes CodingKeys, init(from:) and encode(to:), and that every stored property's type must conform.

for a middle

Explain the per-property rules: Optional uses decodeIfPresent, a missing non-optional key throws keyNotFound, and a var default does not make the key optional.

for a senior

Point out the quiet traps in review: a let with an initial value that is never decoded, defaults that look like fallbacks, and conformances added in another file.

for a principal

Treat which fields the server may omit as part of the contract, and make the Swift types state it with Optional or explicit fallbacks rather than defaults.

## What `Codable` is `Codable` is not a protocol of its own. The standard library declares it as a **typealias**: `public typealias Codable = Encodable & Decodable`. `Encodable` requires one method, `encode(to:)`, which writes a value into an `Encoder`; `Decodable` requires one initializer, `init(from:)`, which builds a value from a `Decoder`. `JSONDecoder` and `JSONEncoder` from Foundation are the coders most apps use, but the protocols themselves know nothing about JSON. ## What the compiler generates When a struct, an enum or a class declares `Codable` in its own declaration, or in an extension **in the same file**, the compiler writes three things for you at compile time: - a nested **`CodingKeys`** enum that conforms to `CodingKey`, with one case per stored property, whose string value is the property name; - **`init(from:)`**, which opens a keyed container and decodes every property listed in `CodingKeys`; - **`encode(to:)`**, which writes every listed property back under the same keys. Nothing is discovered by reflection at run time: the generated code is ordinary Swift, checked by the type checker like code you wrote yourself. ## When synthesis is refused The compiler only synthesizes when it can prove the generated code type-checks: 1. Every stored property it must decode needs a type that itself conforms. `String`, the integer and floating-point types, `Bool`, `Date`, `URL`, `Data`, and arrays, dictionaries and optionals of conforming types all do; a property of your own non-`Codable` type does not, and the compiler's note says it cannot automatically synthesize `Decodable` because that property does not conform. 2. The conformance must be declared in the type's own file. Declaring `extension Weather: Codable {}` in another file fails with "extension outside of file declaring struct 'Weather' prevents automatic synthesis of 'init(from:)' for protocol 'Decodable'". 3. If you write `CodingKeys` yourself and leave a property out, that property needs a default value, or the note reads "does not have a matching CodingKey and does not have a default value". ## How each kind of property decodes | Declaration | Key missing | Key is `null` | Wrong JSON type | |---|---|---|---| | `let city: String` | `keyNotFound` | `valueNotFound` | `typeMismatch` | | `var humidity: Int?` | `nil` | `nil` | `typeMismatch` | | `var units: String = "metric"` | `keyNotFound` | `valueNotFound` | `typeMismatch` | | `let id = 7` | never decoded | never decoded | never decoded | The second row is the one that matters most in practice: the synthesized initializer calls **`decodeIfPresent`** for an `Optional` property, so a missing key or a JSON `null` becomes `nil`. A value of the wrong type is still an error, because `decodeIfPresent` throws `typeMismatch` rather than swallowing the value. The third row surprises people. A default value on a `var` does **not** make the key optional: the synthesized `init(from:)` decodes every property in `CodingKeys` with `decode`, and the initial value is only used by other initializers. If the server may omit the field, make it `Optional` or write `init(from:)` yourself with `decodeIfPresent(_:forKey:) ?? "metric"`. The fourth row is a `let` with an initial value. It cannot be overwritten, so the compiler leaves it out of decoding and warns: "immutable property will not be decoded because it is declared with an initial value which cannot be overwritten". It is still encoded. ## Decoding a flat weather object ```swift struct Weather: Codable { let city: String let tempC: Double var humidity: Int? } let weather = try JSONDecoder().decode(Weather.self, from: data) ``` With the default settings, JSON keys must match the property names exactly, including case: `tempC` matches only `"tempC"`. Renaming keys is the job of `CodingKeys` raw values or the decoder's key strategy. ## The encoding side The synthesized `encode(to:)` mirrors the decoder. An `Optional` property that is `nil` is written with `encodeIfPresent`, so the key is simply omitted rather than written as `null`. Every other listed property is always written, including a `let` with an initial value. ## Habits that find a failing decode fast When a first decode fails, in a take-home exercise or a new feature, three habits find the cause in minutes: - **Print the caught error**, not a generic "failed to load" message: it names the `DecodingError` case and the key or type involved. - **Compare names character by character.** `tempC` and `temp_c`, or `id` and `ID`, are different keys to a decoder at its default settings. - **Decide per field whether the server may omit it**, and make exactly those properties `Optional`. Making everything optional hides real contract breaks; making nothing optional turns every missing field into a failed screen. These are the same three facts the synthesized code encodes: exact keys, conforming types, and `Optional` as the only built-in way to say "may be absent".

  • Why does a `var units: String = "metric"` property still throw keyNotFound when the JSON omits it?
    The synthesized `init(from:)` decodes every property listed in `CodingKeys` with `decode`, which throws when the key is missing; the initial value is used only by other initializers. To fall back, make the property `Optional`, or write `init(from:)` yourself and use `try container.decodeIfPresent(String.self, forKey: .units) ?? "metric"`.
  • What happens to `let id = 7` in a struct with synthesized Codable?
    It is never decoded, because a `let` with an initial value cannot be overwritten, and the compiler warns that the immutable property will not be decoded. It is still encoded. The warning's notes suggest setting the value through the initializer, making it a `var`, or writing `CodingKeys` without that case.
  • Can you add `Codable` to a struct in an extension and still get synthesis?
    Yes, if the extension is in the same file as the struct. In another file the compiler refuses with an error that the extension outside of the file declaring the struct prevents automatic synthesis of `init(from:)`, and you must write `init(from:)` and `encode(to:)` yourself.

  • A property with a default value may be missing from the JSON under synthesized Codable.
  • Making a property Optional makes the decoder ignore a value of the wrong type.
  • Codable finds property names by reflection at run time.
  • Every Codable struct needs a hand-written CodingKeys enum.
  • Codable synthesis works from an extension in any file of the module.
open as a page

With Swift's JSONDecoder, how do CodingKeys and the .convertFromSnakeCase key strategy map snake_case keys, and why does combining them often throw keyNotFound?

level: middleimportance: must knowfreq 70%

basics

~20 s

CodingKeys raw values rename or skip properties; .convertFromSnakeCase rewrites each JSON key to camelCase before matching them. Combined, a raw value like "user_id" or a property named imageURL no longer matches the converted key, so decoding throws keyNotFound.

open as a page

After a server release, a Swift app's forecast list decode throws DecodingError.dataCorrupted at path [3].condition; what happened, and how do you make the decode tolerant?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The fourth element's condition held a string no case of the String raw-value enum accepts, so synthesized decoding threw dataCorrupted and failed the whole array. A custom init(from:) mapping unknown strings to a case like unrecognized(String) makes it tolerant.

open as a page

Why does Swift's JSONDecoder at default settings throw typeMismatch on an ISO 8601 date string, and which dateDecodingStrategy fixes it?

level: middleimportance: should knowfreq 55%

basics

~20 s

The default .deferredToDate lets Date decode itself, which expects a number of seconds since 1 January 2001, so a string throws typeMismatch. Set dateDecodingStrategy to .iso8601, or to .custom when one payload mixes date formats.

open as a page

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:)?

level: seniorimportance: should knowfreq 50%

basics

~20 s

In 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.

open as a page

Should a Swift app's domain models conform to Codable directly, or should separate transfer types decode the API and be mapped into them?

level: principalimportance: should knowfreq 40%

basics

~20 s

Codable on domain models is cheapest when the app owns a stable format. For third-party or changing APIs, Decodable transfer types that mirror the JSON, mapped into domain types, keep CodingKeys, envelopes and open enums out of the model.

open as a page