Skip to content

Instantly share code, notes, and snippets.

@eneko
Created November 18, 2024 17:18
Show Gist options
  • Save eneko/2d595bf044180fcb9b54a04694659835 to your computer and use it in GitHub Desktop.
Save eneko/2d595bf044180fcb9b54a04694659835 to your computer and use it in GitHub Desktop.
Codable with snake_case conversion gotcha
/// If you work with Codable and use automatic `snake_case` conversion
/// when encoding/decoding objects, you might have found that `fooId`
/// works both ways, however `fooID` does not.
///
/// Issue: decoder fails to convert `snake_id` to `snakeID`
///
import Foundation
struct Snake: Codable {
var snakeID: UUID
var name: String
}
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let snake = Snake(snakeID: UUID(), name: "Foo Snake")
let data = try encoder.encode(snake)
let decoded = try decoder.decode(Snake.self, from: data)
} catch {
dump(error)
}
/// Error output:
/// ```
/// ▿ Swift.DecodingError.keyNotFound
/// ▿ keyNotFound: (2 elements)
/// - .0: CodingKeys(stringValue: "snakeID", intValue: nil)
/// ▿ .1: Swift.DecodingError.Context
/// - codingPath: 0 elements
/// - debugDescription: "No value associated with key CodingKeys(stringValue: \"snakeID\", intValue: nil) (\"snakeID\")."
/// - underlyingError: nil
/// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment