tezvyn:

Map JSON keys to differently named Codable properties

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

Codable key customization.

OUTLINE

declare a nested CodingKeys enum mapping userID to the raw value "user_id", or set the decoder's keyDecodingStrategy to convertFromSnakeCase for blanket conversion.

WHAT THIS TESTS This checks practical Codable knowledge, specifically how to keep idiomatic Swift names while matching an external JSON contract you do not control. It also probes whether you know the per-key versus whole-payload approaches.

A GOOD ANSWER COVERS The targeted approach is a CodingKeys enum nested in the type, conforming to String and CodingKey. When you provide it, you must list every coded property; cases whose names match the JSON need no raw value, while userID gets a raw value of "user_id". The compiler then synthesizes encoding and decoding using those keys, so you keep the camelCase property. The broad approach is to configure the decoder once with decoder.keyDecodingStrategy = .convertFromSnakeCase, which transforms all snake_case JSON keys into camelCase before matching, so user_id maps to userID across the entire model graph with no per-property work. Choose CodingKeys when only a few keys differ or names are irregular, and the strategy when the whole API is consistently snake_case. Both avoid renaming the Swift property or dropping to manual parsing.

COMMON WRONG ANSWERS Renaming the property to user_id, which pollutes Swift code with non-idiomatic names. Writing a full custom init(from decoder:) when a CodingKeys map suffices. Forgetting that once you declare CodingKeys you must include every property, or some stop decoding.

LIKELY FOLLOW-UPS What happens if you omit a property from CodingKeys? When does convertFromSnakeCase fail on irregular keys? Can you combine both approaches? How do you also encode with a snake_case strategy?

ONE CONCRETE EXAMPLE For struct User: Codable { let userID: Int; let name: String }, add enum CodingKeys: String, CodingKey { case userID = "user_id"; case name }. Decoding {"user_id": 7, "name": "Ann"} now fills userID with 7. If the entire API is snake_case, you could instead drop CodingKeys and set the decoder's keyDecodingStrategy to convertFromSnakeCase, achieving the same mapping globally.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.