0Pricing
Swift Academy · Lesson

Key and Date Decoding Strategies

Use snake_case and date strategies.

Decoding Strategies Overview

Instead of writing a CodingKeys enum for every type, you can set a global strategy on the decoder. Strategies transform keys and parse dates uniformly across all decoded types.

import Foundation

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
print("Strategy configured")

convertFromSnakeCase

Setting keyDecodingStrategy = .convertFromSnakeCase automatically maps keys like first_name to the camelCase property firstName — no CodingKeys needed.

import Foundation

struct User: Codable {
    var firstName: String
    var lastName: String
}

let json = "{\"first_name\":\"Ada\",\"last_name\":\"Lovelace\"}"
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let u = try decoder.decode(User.self, from: json.data(using: .utf8)!)
print(u.firstName, u.lastName)

All lessons in this course

  1. CodingKeys for Renaming
  2. Key and Date Decoding Strategies
  3. Manual encode(to:) and init(from:)
  4. Decoding Heterogeneous JSON
← Back to Swift Academy