Implement Swift Codable models for JSON and property-list encoding and decoding with JSONDecoder, JSONEncoder, CodingKeys, and custom init(from:) or…
Swift Codable
Encode and decode Swift types using Codable (Encodable & Decodable) with
JSONEncoder, JSONDecoder, and related APIs. Targets Swift 6.3 / iOS 26+.
Contents
Decode and Verify Workflow
Basic Conformance
Custom CodingKeys
Custom Decoding and Encoding
Nested and Flattened Containers
Heterogeneous Arrays
Date Decoding Strategies
Data and Key Strategies
Lossy Array Decoding
Single Value Containers
Default Values for Missing Keys
Encoder and Decoder Configuration
Codable with URLSession
Codable with SwiftData
Codable with UserDefaults
Common Mistakes
Review Checklist
References
Decode and Verify Workflow
Decode representative success, missing, null, malformed, acronym-key, and
date fixtures.
On failure, inspect DecodingError, its codingPath, and the raw payload.
Correct only the mismatched model, key, container, or strategy; do not hide
contract failures with lossy decoding.
Rerun fixtures and encode/decode round trips where both directions are part
of the contract.
Basic Conformance
When all stored properties are themselves Codable, the compiler synthesizes
conformance automatically:
struct User: Codable {
let id: Int
let name: String
let email: String
let isVerified: Bool
}
let user = try JSONDecoder().decode(User.self, from: jsonData)
let encoded = try JSONEncoder().encode(user)
Prefer Decodable for read-only API responses and Encodable for write-only.
Use Codable only when both directions are required.
Custom CodingKeys
Rename JSON keys without writing a custom decoder by declaring a CodingKeys
enum:
struct Product: Codable {
let id: Int
let displayName: String
let imageURL: URL
let priceInCents: Int
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
case imageURL = "image_url"
case priceInCents = "price_in_cents"
}
}
Every stored property must appear in the enum. Omitting a property from
CodingKeys excludes it from encoding/decoding -- provide a default value or
compute it separately.
Custom Decoding and Encoding
Override init(from:) and encode(to:) for transformations the synthesized
conformance cannot handle:
struct Event: Codable {
let name: String
let timestamp: Date
let tags: [String]
enum CodingKeys: String, CodingKey {
case name, timestamp, tags
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// Decode Unix timestamp as Double, convert to Date
let epoch = try container.decode(Double.self, forKey: .timestamp)
timestamp = Date(timeIntervalSince1970: epoch)
// Default to empty array when key is missing
tags = try container.decodeIfPresent([String].self, forKey: .tags) ?? []
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(timestamp.timeIntervalSince1970, forKey: .timestamp)
try container.encode(tags, forKey: .tags)
}
}
Nested and Flattened Containers
Use nestedContainer(keyedBy:forKey:) to navigate and flatten nested JSON:
// JSON: { "id": 1, "location": { "lat": 37.7749, "lng": -122.4194 } }
struct Place: Decodable {
let id: Int
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey { case id, location }
enum LocationKeys: String, CodingKey { case lat, lng }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
let location = try container.nestedContainer(
keyedBy: LocationKeys.self, forKey: .location)
latitude = try location.decode(Double.self, forKey: .lat)
longitude = try location.decode(Double.self, forKey: .lng)
}
}
Chain multiple nestedContainer calls to flatten deeply nested structures.
Also use nestedUnkeyedContainer(forKey:) for nested arrays.
Heterogeneous Arrays
Load Advanced Codable Patterns
for discriminator-based mixed arrays.
Date Decoding Strategies
Configure JSONDecoder.dateDecodingStrategy to match your API:
let decoder = JSONDecoder()
// ISO 8601 (e.g., "2024-03-15T10:30:00Z")
decoder.dateDecodingStrategy = .iso8601
// Unix timestamp in seconds (e.g., 1710499800)
decoder.dateDecodingStrategy = .secondsSince1970
// Custom DateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .formatted(formatter)
// Custom closure for multiple formats
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = ISO8601DateFormatter().date(from: string) { return date }
throw DecodingError.dataCorruptedError(
in: container, debugDescription: "Cannot decode date: \(string)")
}
Set the matching strategy on JSONEncoder:
encoder.dateEncodingStrategy = .iso8601
Data and Key Strategies
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64 // Base64-encoded Data fields
decoder.keyDecodingStrategy = .convertFromSnakeCase // simple keys only; not URL/ID spelling
// {"user_name": "Alice"} maps to `var userName: String` -- no CodingKeys needed
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.keyEncodingStrategy = .convertToSnakeCase
Use key strategies only for mechanical snake_case-to-camelCase mappings.
convertFromSnakeCase maps by spelling, not Swift acronym/initialism policy:
image_url, base_uri, and user_id match imageUrl, baseUri, and
userId only. If the Swift model uses imageURL, baseURI, or userID,
declare explicit CodingKeys; the strategy will not synthesize those names.
Lossy Array Decoding
Use lossy arrays only when partial success is part of the product contract; load
Lossy Arrays.
Single Value Containers
Use singleValueContainer() for type-safe primitive wrappers; see
Single-Value Wrappers.
Default Values for Missing Keys
Stored defaults do not make synthesized decoding tolerate missing nonoptional
keys. Load Missing-Key Defaults
when the contract assigns explicit fallback behavior to missing or null values.
Encoder and Decoder Configuration
Keep matching strategies at the transport/file-format boundary. Load
Encoder Configuration
for nonconforming floats and property-list guidance.
Codable with URLSession
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse,
(200...299).contains(http.statusCode) else {
throw APIError.invalidResponse
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(User.self, from: data)
}
// Generic API envelope. Configure a decoder inside this helper because
// fetchUser's decoder is out of scope.
struct APIResponse<T: Decodable>: Decodable {
let data: T
let meta: Meta?
struct Meta: Decodable { let page: Int; let totalPages: Int }
}
func decodeUsersEnvelope(from data: Data) throws -> [User] {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(APIResponse<[User]>.self, from: data).data
}
Codable with SwiftData
Keep schema values typed and route persistence design to swiftdata; see
Persistence Boundaries.
Codable with UserDefaults
Use primitives for small preferences. Load
Persistence Boundaries
for a small Codable RawRepresentable/@AppStorage handoff; use a real
persistence layer for larger or durable data.
Common Mistakes
1. Not handling missing defaulted fields:
// DON'T -- crashes if key is absent
let value = try container.decode(String.self, forKey: .bio)
// DO -- falls back when the key is absent or null
let value = try container.decodeIfPresent(String.self, forKey: .bio) ?? ""
2. Failing entire array when one element is invalid:
// DON'T -- one bad element kills the whole decode
let items = try container.decode([Item].self, forKey: .items)
// DO -- decode elements individually only when partial success is allowed
3. Date strategy mismatch:
// DON'T -- default strategy expects Double, but API sends ISO string
let decoder = JSONDecoder() // dateDecodingStrategy defaults to .deferredToDate
// DO -- set strategy to match your API format
decoder.dateDecodingStrategy = .iso8601
4. Force-unwrapping decoded optionals:
// DON'T
let user = try? decoder.decode(User.self, from: data)
print(user!.name)
// DO
guard let user = try? decoder.decode(User.self, from: data) else { return }
5. Using Codable when only Decodable is needed:
// DON'T -- unnecessarily constrains the type to also be Encodable
struct APIResponse: Codable { let id: Int; let message: String }
// DO -- use Decodable for read-only API responses
struct APIResponse: Decodable { let id: Int; let message: String }
6. Manual CodingKeys for simple snake_case APIs:
// DON'T -- verbose boilerplate for every model
enum CodingKeys: String, CodingKey {
case userName = "user_name"
case avatarUrl = "avatar_url"
}
// DO -- configure once on the decoder for simple cases
decoder.keyDecodingStrategy = .convertFromSnakeCase
// Keep CodingKeys for `imageURL`, `baseURI`, `userID`, and similar names.
Review Checklist
Types conform to Decodable only when encoding is not needed
decodeIfPresent used with defaults for optional or missing keys
keyDecodingStrategy = .convertFromSnakeCase used for simple snake_case APIs, with CodingKeys retained for acronym spellings
dateDecodingStrategy matches the API date format
Arrays of unreliable data use lossy decoding to skip invalid elements
Custom init(from:) validates and transforms data instead of post-decode fixups
JSONEncoder.outputFormatting includes .sortedKeys for deterministic test output
Wrapper types (UserID, etc.) use singleValueContainer for clean JSON
Generic APIResponse<T> wrapper used for consistent API envelope handling
No force-unwrapping of decoded values
Persistence boundary is explicit: SwiftData only for compatible noncomputed model properties, @AppStorage/UserDefaults only for small primitive or RawRepresentable preferences
References
Advanced Codable patterns -- mixed arrays, lossy decoding, wrappers, defaults, configuration, and persistence boundaries
Codable -- protocol combining Encodable and Decodable
JSONDecoder -- decodes JSON data into Codable types
JSONEncoder -- encodes Codable types as JSON data
CodingKey -- protocol for encoding/decoding keys
JSONDecoder.KeyDecodingStrategy.convertFromSnakeCase -- snake-case conversion behavior and limitations
Encoding and Decoding Custom Types -- Apple guide on custom Codable conformance
Using JSON with Custom Types -- Apple sample code for JSON patterns
Preserving your app's model data across launches -- SwiftData model property compatibilitydon't have the plugin yet? install it then click "run inline in claude" again.
restructured original reference material into 10 concrete numbered steps with explicit inputs and outputs, extracted implicit decision logic into 17 if-else branches covering date formats, missing keys, array handling, api envelopes, and persistence layers, added edge cases for rate limits and network timeouts, clarified that keydecoding strategy does not handle acronyms, and added outcome signals for test coverage and round-trip validation.
encode and decode swift types using codable (encodable & decodable) with jsondecoder, jsonencoder, and related apis. use this skill when you need to transform json or plist payloads into strongly-typed swift objects, handle mismatched key names between your api and model layer, apply custom transformations (date formats, nested flattening, lossy arrays), and round-trip data bidirectionally. targets swift 6.3+, ios 18+.
inputs: struct/class definition, list of properties
outputs: type that conforms to codable (auto-synthesized)
when all stored properties are themselves codable, the compiler synthesizes conformance automatically:
struct User: Codable {
let id: Int
let name: String
let email: String
let isVerified: Bool
}
prefer decodable for read-only api responses and encodable for write-only. use codable only when both directions are required by the contract.
inputs: json key names from api, property names in swift model
outputs: codingkeys enum mapping swift names to json keys
when json uses snake_case but swift uses camelCase, declare a codingkeys enum:
struct Product: Codable {
let id: Int
let displayName: String
let imageURL: URL
let priceInCents: Int
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
case imageURL = "image_url"
case priceInCents = "price_in_cents"
}
}
every stored property must appear in the enum. omitting a property from codingkeys excludes it from encoding/decoding.
alternatively, configure the decoder with keydecoding strategy:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
use keydecoding strategy only for mechanical snake_case-to-camelCase mappings. if the swift model uses acronyms (imageURL, baseURI, userID), keep explicit codingkeys because the strategy maps by spelling, not acronym policy.
inputs: api date format string or strategy enum, data encoding (e.g., base64)
outputs: configured jsondecoder ready to handle dates and binary data
match the decoder strategy to the api format:
let decoder = JSONDecoder()
// iso 8601 (e.g., "2024-03-15t10:30:00z")
decoder.dateDecodingStrategy = .iso8601
// unix timestamp in seconds (e.g., 1710499800)
decoder.dateDecodingStrategy = .secondsSince1970
// custom dateformatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .formatted(formatter)
// custom closure for multiple formats
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
if let date = ISO8601DateFormatter().date(from: string) { return date }
throw DecodingError.dataCorruptedError(
in: container, debugDescription: "cannot decode date: \(string)")
}
// base64-encoded data fields
decoder.dataDecodingStrategy = .base64
inputs: decoder, codingkeys enum, logic to transform raw values
outputs: fully initialized instance with computed or transformed properties
override init(from:) when synthesized conformance cannot handle your transformation:
struct Event: Codable {
let name: String
let timestamp: Date
let tags: [String]
enum CodingKeys: String, CodingKey {
case name, timestamp, tags
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// decode unix timestamp as double, convert to date
let epoch = try container.decode(Double.self, forKey: .timestamp)
timestamp = Date(timeIntervalSince1970: epoch)
// default to empty array when key is missing
tags = try container.decodeIfPresent([String].self, forKey: .tags) ?? []
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(timestamp.timeIntervalSince1970, forKey: .timestamp)
try container.encode(tags, forKey: .tags)
}
}
use decodeIfPresent instead of decode for optional or missing keys. validate and transform data inside init(from:), not in post-decode fixups.
inputs: decoder, nested codingkeys enum, path to nested object
outputs: flattened properties extracted from nested structure
use nestedcontainer(keyedby:forkey:) to navigate and flatten nested json:
// json: { "id": 1, "location": { "lat": 37.7749, "lng": -122.4194 } }
struct Place: Decodable {
let id: Int
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey { case id, location }
enum LocationKeys: String, CodingKey { case lat, lng }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
let location = try container.nestedContainer(
keyedBy: LocationKeys.self, forKey: .location)
latitude = try location.decode(Double.self, forKey: .lat)
longitude = try location.decode(Double.self, forKey: .lng)
}
}
chain multiple nestedcontainer calls to flatten deeply nested structures. use nestedunkeyedcontainer(forkey:) for nested arrays.
inputs: decoder, primitive value to wrap
outputs: type-safe wrapper (e.g., userID, articleslug)
use singlevaluecontainer() for wrapper types to keep json clean:
struct UserID: Codable {
let value: Int
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(Int.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
}
// json: 42 decodes to UserID(value: 42)
inputs: array of items, some of which may be malformed
outputs: array containing only valid elements (invalid ones skipped)
decode array elements individually only when partial success is allowed by the contract:
struct APIResponse: Decodable {
let items: [Item]
enum CodingKeys: String, CodingKey { case items }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var itemsArray: [Item] = []
if var unkeyedContainer = try? container.nestedUnkeyedContainer(forKey: .items) {
while !unkeyedContainer.isAtEnd {
if let item = try? unkeyedContainer.decode(Item.self) {
itemsArray.append(item)
} else {
_ = try unkeyedContainer.decode(AnyCodable.self) // skip invalid
}
}
}
items = itemsArray
}
}
use lossy arrays only when the product contract explicitly allows partial success. do not hide contract failures with lossy decoding.
inputs: url, decoder configuration, expected response envelope type
outputs: decoded model extracted from api response
fetch and decode from an api endpoint:
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse,
(200...299).contains(http.statusCode) else {
throw APIError.invalidResponse
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(User.self, from: data)
}
// generic api envelope
struct APIResponse<T: Decodable>: Decodable {
let data: T
let meta: Meta?
struct Meta: Decodable { let page: Int; let totalPages: Int }
}
func decodeUsersEnvelope(from data: Data) throws -> [User] {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(APIResponse<[User]>.self, from: data).data
}
inputs: codable instance, encoder configuration
outputs: json or plist data ready for transport
match encoder strategies to the decoder:
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
encoder.dataEncodingStrategy = .base64
encoder.keyEncodingStrategy = .convertToSnakeCase
let encoded = try encoder.encode(user)
include .sortedkeys for deterministic test output. set the matching strategy on both encoder and decoder to ensure round-trip fidelity.
inputs: json fixtures covering success, missing, null, malformed, acronym-key, and date formats
outputs: confirmed model instances or handled decodingerror
decode representative success, missing, null, malformed, acronym-key, and date fixtures:
func testDecodeUser() throws {
let json = """
{"id": 1, "name": "alice", "email": "alice@example.com", "is_verified": true}
""".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let user = try decoder.decode(User.self, from: json)
XCTAssertEqual(user.id, 1)
}
func testRoundTrip() throws {
let original = User(id: 1, name: "alice", email: "alice@example.com", isVerified: true)
let encoded = try JSONEncoder().encode(original)
let decoded = try JSONDecoder().decode(User.self, from: encoded)
XCTAssertEqual(original.id, decoded.id)
XCTAssertEqual(original.name, decoded.name)
}
on failure, inspect decodingerror, its codingpath, and the raw payload. correct only the mismatched model, key, container, or strategy. do not hide contract failures with lossy decoding. rerun fixtures and encode/decode round trips where both directions are part of the contract.
if the json uses simple snake_case consistently: configure keydecoding strategy on the decoder. omit explicit codingkeys to reduce boilerplate.
if the json uses acronyms (imageurl, baseuri, userid) or mixed conventions: declare explicit codingkeys instead, because keydecoding strategy maps by spelling and will not synthesize acronym names.
if the api returns dates as iso 8601 strings: set decoder.datedecodingstrategy = .iso8601.
if the api returns dates as unix timestamps: set decoder.datedecodingstrategy = .secondssince1970 or .millisecondssince1970.
if the api returns dates in a custom format: create a dateformatter with the exact format string and configure decoder.datedecodingstrategy = .formatted(formatter). test with explicit locale and timezone.
if the api returns custom date formats and you need to try multiple parsers: use decoder.datedecodingstrategy = .custom { decoder in ... } to attempt each format and throw a clear decodingerror if all fail.
if a required key is missing and you have a sensible default: use decodeifpresent with ?? fallback. do not rely on stored property defaults; synthesized decoding does not tolerate missing nonoptional keys.
if a json field is optional or may be null: decode it with decodeifpresent and provide a fallback (nil, empty array, zero, etc.). do not use decode on optional keys.
if the api response wraps your data in an envelope (e.g., { "data": [...], "meta": {...} }): create a generic wrapper struct apiresonse<t: decodable> and decode the envelope first, then extract the inner type.
if an array may contain malformed elements and partial success is acceptable: decode array elements individually in init(from:) with lossy skipping. only use this when the contract explicitly allows data loss.
if an array element is guaranteed to fail if one element is invalid: decode the whole array with decode([item].self, forkey:); let the error propagate to the caller.
if you need both encoding and decoding: use codable. if only decoding is needed for api responses, use decodable. if only encoding is needed for requests, use encodable.
if you are persisting to swiftdata: keep only codable properties that swiftdata supports (no computed properties, no lazy properties, no transient fields). do not encode the entire swiftdata model; map codable properties explicitly.
if you are persisting to userdefaults: use primitives or rawrepresentable types with @appstorage. do not encode large codable objects to userdefaults; use swiftdata or a real persistence layer.
if the api returns non-conforming floats (nan, infinity): configure encoder/decoder with the nonconformingfloatstrategy.