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?
answer
- four DecodingError cases
- codingPath with zero-based indices
- init?(rawValue:) returned nil
- one bad element fails the array
- a case that keeps the raw string
basics
~20 sThe 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.
solid answer
~40 s`DecodingError` has four cases: `keyNotFound`, `valueNotFound`, `typeMismatch` and `dataCorrupted`, each with a context holding `codingPath` and `debugDescription`. A path of `[Index 3, condition]` points at the `condition` key of the fourth array element. For a `String` raw-value enum, synthesized decoding reads a string and calls `init?(rawValue:)`; a new server value such as `"hail"` returns `nil`, which becomes `dataCorrupted` with "Cannot initialize Condition from invalid String value hail". The error propagates, so the whole `[Observation]` decode fails. The fix is a hand-written `init(from:)` on the enum that reads a `singleValueContainer()` and maps unknown strings to `case unrecognized(String)`, which keeps the value, or to an `unknown` sentinel, which loses it. Since Swift 6.3, `print(error)` shows this as one readable line on runtimes that include it.
code
swift · 22 linesimport Foundation
enum Condition: Decodable, Equatable {
case sunny, cloudy, rain
case unrecognized(String)
init(from decoder: any Decoder) throws {
let raw = try decoder.singleValueContainer().decode(String.self)
switch raw {
case "sunny": self = .sunny
case "cloudy": self = .cloudy
case "rain": self = .rain
default: self = .unrecognized(raw)
}
}
}
struct Observation: Decodable { let condition: Condition }
let json = #"[{"condition": "rain"}, {"condition": "hail"}]"#
let list = try JSONDecoder().decode([Observation].self, from: Data(json.utf8))
print(list.map(\.condition)) // rain, then unrecognized("hail")go deeper
Recall the four DecodingError cases and that codingPath shows where in the JSON decoding failed.
Explain why a raw-value enum throws dataCorrupted on an unknown string and how errors propagate up through the array decode.
Diagnose from the case and path alone, then pick the right tolerance: a case that keeps the raw value, a sentinel, or a lossy collection with logging.
Agree with the API owners which enums may grow, and make tolerance a per-field rule so safe fields degrade and critical ones still fail loudly.
## Reading the error first A `DecodingError` is an enum with four cases, and each one names a different kind of mismatch. Every case carries a `DecodingError.Context` with three fields: **`codingPath`**, the keys and array indices from the root to the failure; **`debugDescription`**, the decoder's own message; and an optional **`underlyingError`**. | Case | Associated values | Meaning | |---|---|---| | `keyNotFound` | the missing `CodingKey`, context | a keyed container had no entry for a required key | | `valueNotFound` | the expected type, context | a `null` where a non-optional value was required (JSONDecoder also uses it when an unkeyed container runs out of elements) | | `typeMismatch` | the expected type, context | the JSON held a different kind of value, such as a string for a `Double` | | `dataCorrupted` | context | the value had the right JSON type but was invalid, such as a string no enum case accepts or a malformed date | `codingPath` lists each step as a `CodingKey`. Array positions appear as keys whose string value is `"Index 3"` and whose `intValue` is `3`, counted from zero, so `[Index 3, condition]` is the `condition` key of the **fourth** element. ## What happened with `[3].condition` The model declared `enum Condition: String, Codable { case sunny, cloudy, rain }`. For a `String` raw-value enum, the synthesized `init(from:)` decodes a `String` and calls `init?(rawValue:)`. The server started sending `"hail"`, the failable initializer returned `nil`, and the decoder threw `dataCorrupted` with the description "Cannot initialize Condition from invalid String value hail". Two properties of Swift decoding turn one new string into a blank screen: - **Errors propagate.** The failing `init(from:)` throws into its caller, the `Observation` initializer, which throws into the array's decode, which throws out of `JSONDecoder.decode`. Nothing is partially returned. - **One bad element fails the whole array.** `[Observation]` decodes each element in turn and has no notion of skipping one. ## Making the enum tolerant Give the enum its own `init(from:)` and decide what an unknown value becomes: 1. **A case that keeps the raw string**, `case unrecognized(String)`, as in the example. The app can show a generic icon, log the value, and re-encode it faithfully if it writes an `encode(to:)` that emits the stored string. 2. **A sentinel case on a raw-value enum**, `case unknown`, with `self = Condition(rawValue: raw) ?? .unknown`. Simpler, but the server's string is lost: encoding writes `"unknown"`. 3. **A lossy collection**: decode each element through a wrapper that catches the error and stores `nil`, then `compactMap` the result. Use this when a whole record may be malformed, not just one enum value, and log what you dropped. Tolerance is a product decision per field. An unknown weather condition can safely degrade; an unknown currency code in a payment payload probably should not. ## A triage routine When a decode that used to work starts failing in production: 1. Read the **case**: it tells you whether a key vanished, a value became `null`, a type changed, or a value became invalid. 2. Read the **path**: it names the element and the field, so you can fetch that exact record. 3. Compare with a **recorded payload** from before the change, and decide whether the server broke the contract or the contract was always looser than the model assumed. 4. Fix at the narrowest point, one enum or one field, and add the new payload to the decode tests. ## Logging the error usefully Swift 6.3 added a readable `debugDescription` for `DecodingError` (SE-0489). On an OS whose Swift runtime includes it, `print(error)` gives one line such as `DecodingError.dataCorrupted: Data was corrupted. Path: [3].condition. Debug description: Cannot initialize Condition from invalid String value hail`. On older runtimes the same call prints the nested enum and context dump. The format is documented as not guaranteed to stay stable, so log it for humans and switch over the cases in code. ## Related enum synthesis Enums **with associated values** also get synthesized `Codable` since Swift 5.5 (SE-0295): `case circle(radius: Double)` encodes as `{"circle": {"radius": 2}}`, unlabeled values use keys `_0`, `_1`, and a case without values encodes as `{"point": {}}`. That shape suits files the app writes for itself; a server that sends bare strings needs the hand-written `init(from:)` above.
- When does `JSONDecoder` throw `valueNotFound` instead of `keyNotFound`?`keyNotFound` means the key is absent from the object. `valueNotFound` means the key is present but holds `null` where a non-optional value was required; JSONDecoder also uses it when an unkeyed container runs out of elements before the decode finishes.
- Why might a `case unknown` sentinel on a `String` raw-value enum be the wrong choice?Encoding writes the raw value `"unknown"`, so the server's actual string is lost when the model is cached or sent back. A `case unrecognized(String)` keeps it, and a matching `encode(to:)` writes it out unchanged.
- How do you keep the other elements when one record in an array is malformed?Decode each element through a small wrapper whose `init(from:)` catches the error and stores `nil`, then `compactMap` the wrappers. Log each dropped element's error, because silent drops hide server bugs.
- A String raw-value enum ignores values it has no case for.
- The index in codingPath counts array elements from one.
- An unknown enum string is reported as typeMismatch.
- JSONDecoder returns the elements it could decode and skips the rest.
- The debugDescription format is stable enough to parse in code.
Assumes Swift 6.4; DecodingError's readable debugDescription (SE-0489) arrived in Swift 6.3 and needs an OS whose Swift runtime includes it.