Should a Swift app's domain models conform to Codable directly, or should separate transfer types decode the API and be mapped into them?
answer
- who owns the format
- quirks leak into the model
- a mapping step at the boundary
- API shape versus disk shape
basics
~20 sCodable 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.
solid answer
~50 sIt depends on who owns the format. When the app writes and reads the format itself, conforming domain models to `Codable` is simplest: one type, mostly synthesized. When the JSON comes from an API you do not control, every quirk, `CodingKeys` for snake_case, a `data` envelope, string enums that may grow, fields that are sometimes missing, lands on the type every screen uses, and invariants weaken as properties turn `Optional`. A transfer layer of synthesized `Decodable` structs that mirror the wire, plus a mapping initializer into domain types, keeps those quirks at the boundary and lets the model use `Measurement`, rich enums and non-optional properties. The cost is a second type per concept and mapping tests. Many teams start with Codable models and add a transfer type per model the first time a wire quirk would leak.
code
swift · 31 linesimport Foundation
// Transfer object: mirrors the wire and owns every wire quirk.
struct ForecastDTO: Decodable {
let cityName: String
let tempC: Double
let condition: String
let observedAt: Date
}
// Domain model: what the app reasons about; no Codable.
enum Condition { case sunny, cloudy, rain, other(String) }
struct Forecast {
let city: String
let temperature: Measurement<UnitTemperature>
let condition: Condition
let observedAt: Date
init(_ dto: ForecastDTO) {
city = dto.cityName
temperature = Measurement(value: dto.tempC, unit: .celsius)
switch dto.condition {
case "sunny": condition = .sunny
case "cloudy": condition = .cloudy
case "rain": condition = .rain
default: condition = .other(dto.condition)
}
observedAt = dto.observedAt
}
}go deeper
Recall that a model type can conform to Codable itself or be built from a separate Decodable type that mirrors the JSON.
Explain what leaks into a Codable model from a messy API: CodingKeys, envelopes, open enums and optional fields.
Recognize when a model has started bending to the wire format and propose a transfer type for that model, with mapping tests.
Set the boundary rule for the team: where decoding happens, when a transfer type is required, and how persisted formats stay independent of the API.
## The decision Every Swift app that talks to an API has to choose where the **wire format** stops and the **domain model** starts. Two patterns dominate: - **Codable domain models.** The types the app reasons about, `Forecast`, `Condition`, conform to `Codable` directly, with `CodingKeys` and custom `init(from:)` where the JSON disagrees. - **A transfer-object layer.** Plain `Decodable` structs mirror the JSON exactly, usually fully synthesized, and a mapping step converts them into domain types that may not be `Codable` at all. There is no single right answer; the choice depends on who owns the format and how fast it changes. ## What Codable on the model buys and costs **Buys:** one type per concept, no mapping code, and synthesized conformance when the JSON already matches. For a format the app owns end to end, a settings file or a cache it writes and reads itself, this is usually the right call. **Costs**, which grow with the API's distance from the model: 1. **Wire quirks leak into the model.** `CodingKeys` for `city_name`, a `data` envelope, string enums that may gain cases, and fields the server sometimes omits all become properties or code on the type every screen uses. 2. **Invariants weaken.** If the server may omit a field, the model property becomes `Optional` for everyone, even where the app could supply a sensible value at the boundary. 3. **Server changes ripple.** A renamed key or a new date format means editing the model, and every test that builds one. 4. **Two formats collide.** When the same type is also persisted to disk, the API's shape and the cache's shape become one shape, so an API change silently changes what is on disk. ## What a transfer layer buys and costs **Buys:** the DTO absorbs every quirk, often with nothing but synthesis and a configured `JSONDecoder` (`.convertFromSnakeCase`, `.iso8601`). The mapping initializer is the one place to apply fallbacks, convert units into `Measurement`, map unknown strings to `other(String)`, and validate. The domain type stays free to use non-optional properties, rich enums and types that have no JSON form. **Costs:** a second type per concept, mapping code to write and test, and a review discipline so that new fields are added in both places. On a small app with a stable API, that duplication can outweigh the benefit. ## Deciding | Situation | Leaning | |---|---| | Format the app writes and reads itself | Codable on the model, with a version field | | Third-party or fast-moving API | Transfer layer | | Server sends envelopes, snake_case, open enums | Transfer layer | | Internal API whose types are generated or shared with the server team | Codable on generated types, mapped at the edge if the model diverges | | Domain type holds members with no JSON form, such as closures, or whose own Codable shape differs from the wire, such as `Measurement` | Transfer layer | A useful middle ground is to start with Codable models and introduce a DTO **per type** the first time a wire quirk would otherwise land in the model. The rule a lead writes down is less about which pattern and more about where the boundary is: - decoding happens in one networking module, never in views; - the persisted format is defined on purpose, never inherited from the API by accident; - every API model has a test that decodes a recorded payload. ## Moving from one to the other Switching an existing model to a transfer layer does not have to be a rewrite. Introduce the `Decodable` transfer type beside the model, decode into it in the networking code, and add a mapping initializer; the views keep using the model unchanged. Once the model no longer needs `CodingKeys` or a custom `init(from:)`, delete them and drop its `Codable` conformance, unless it is also persisted, in which case decide deliberately which format that file keeps. Doing it one type at a time, starting with the type whose JSON hurts most, keeps the cost proportional to the benefit. ## Testing either way Whichever pattern you choose, keep recorded JSON payloads in the test bundle and decode them in unit tests. With a transfer layer, also test the mapping: an unknown condition maps to `other`, and a missing optional field gets the fallback the product expects. That is where the layer earns its cost.
- Why is it risky to persist the same Codable type the API decodes into?The cache format then follows the API by accident. A server rename changes `CodingKeys`, and data already on disk no longer decodes after the update. Give the persisted format its own type or a version field, so an API change and a storage migration are separate decisions.
- What should the tests of a transfer layer cover?Decoding recorded payloads into the transfer types, and the mapping rules: unknown enum strings, missing optional fields and unit conversions. Those rules are why the layer exists, so they deserve the tests.
A transfer layer is like a translator at a border: documents arrive in the sender's format, and only the translated version enters the country, so a change in the foreign paperwork is the translator's problem, not every citizen's.
- Domain models must never conform to Codable.
- A transfer layer is always worth its cost, even for a format the app owns.
- Making model properties Optional is a free way to absorb API changes.
- Persisting the API's Codable type to disk is safe because both use JSON.