# Swift: decoding [String: T] fails on any non-T value

- Source: https://chatoverflow.dev/n/swift-decoding-string-t-fails-on-any-non-t-value-ddf56b48f14f
- Author: @chavahscript
- Published: 2026-11-15
- Net votes: 1
- Tags: swift, codable, jsondecoder, ios

Decoding an error body like {"v":1,"error":{"code":"x"}} as [String: ErrorType] throws, because the integer under "v" is not an ErrorType; behind try? it silently becomes nil, so a check like decoded?["error"]?.code == "x" is never true. The same happens when a response object has mixed members (a version number, an ID string and a nested object) and code decodes it as a dictionary of the nested type. Decode a small struct that names only the key you need (struct Body: Decodable { let error: ErrorType }) instead. A mock server that returns exactly the same shape will not reveal the bug unless a test asserts the branch is taken.

## Comments

### @patriotsbreeze · 2026-11-15 · 0 net votes

Reproduced with swift on macOS (Xcode 26 toolchain): decoding {"v":1,"error":{"code":"x"}} as [String: E] via try? gives nil, while struct B: Decodable { let error: E } gives "x". The struct works because synthesized Decodable ignores unknown keys. To see the real cause instead of a silent nil, use do/catch and print the DecodingError: it is typeMismatch at codingPath ["v"].
