Skip to content
Mobile
Skill

/swift-codable

Implement Swift Codable models for JSON and property-list encoding and decoding with JSONDecoder, JSONEncoder, CodingKeys, and custom init(from:) or encode(to:). Use when parsing API responses, remapping keys, flattening nested JSON, handling date or data decoding strategies,

From plugin
swift-ios-skills
1.3k86 skills1 MCP

Claude Code

$ npx -y skills add dpearson2699/swift-ios-skills --skill swift-codable --agent claude-code

SKILL.md

swift-codable.SKILL.md
name: swift-codable
description: "Implement Swift Codable models for JSON and property-list encoding and decoding with JSONDecoder, JSONEncoder, CodingKeys, and custom init(from:) or encode(to:). Use when parsing API responses, remapping keys, flattening nested JSON, handling date or data decoding strategies, decoding heterogeneous arrays, or integrating Codable with URLSession, SwiftData, or UserDefaults."

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](#decode-and-verify-workflow)
  • [Basic Conformance](#basic-conformance)
  • [Custom CodingKeys](#custom-codingkeys)
  • [Custom Decoding and Encoding](#custom-decoding-and-encoding)
  • [Nested and Flattened Containers](#nested-and-flattened-containers)
  • [Heterogeneous Arrays](#heterogeneous-arrays)
  • [Date Decoding Strategies](#date-decoding-strategies)
  • [Data and Key Strategies](#data-and-key-strategies)
  • [Lossy Array Decoding](#lossy-array-decoding)
  • [Single Value Containers](#single-value-containers)
  • [Default Values for Missing Keys](#default-values-for-missing-keys)
  • [Encoder and Decoder Configuration](#encoder-and-decoder-configuration)
  • [Codable with URLSession](#codable-with-urlsession)
  • [Codable with SwiftData](#codable-with-swiftdata)
  • [Codable with UserDefaults](#codable-with-userdefaults)
  • [Common Mistakes](#common-mistakes)
  • [Review Checklist](#review-checklist)
  • [References](#references)

Decode and Verify Workflow

1. Decode representative success, missing, null, malformed, acronym-key, and date fixtures. 2. On failure, inspect `DecodingError`, its `codingPath`, and the raw payload. 3. Correct only the mismatched model, key, container, or strategy; do not hide contract failures with lossy decoding. 4. 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](references/codable-advanced-patterns.md#heterogeneous-arrays) 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 { dec
Read more
@dpearson2699
Ships withswift-ios-skills

86 agent skills optimized for iOS 26+ development with Swift 6.3 and modern Apple frameworks.

1.3k86 skills1 MCP
Get the whole plugin

Stars on GitHub

Momentum

stars in total
1.3k
Star history of dpearson2699/swift-ios-skills on GitHub, a chart by star-history.com

Other skills on swift-ios-skills.

alarmkit

alarmkit

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, StandBy, and paired Apple…

app-clips

app-clips

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store…

More skills from other plugins.

deep-code-review

deep-code-review

In-depth design-focused code review - understands codebase context before evaluating PR changes, posts structured feedback to…

expo1d53k
@expo@expoInstall Skill
modlens

modlens

Plug-in vision for text-only models. Hard rule: when a file path or URL with an image extension (.png, .jpg, .jpeg, .webp, .gif,…

modlens2w4.6k
@liustack@liustackInstall Skill
appllama-app-design-skill

appllama-app-design-sk…

Build native-feeling, benchmark-quality mobile app screens (Expo / React Native). Use when designing or implementing any mobile…

appllama2mo3.9k
@appllama@appllamaInstall Skill

Questions about swift-codable.

Which coding agents can use swift-codable?
swift-codable installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.