Codable Models
Use Codable with explicit CodingKeys for JSON serialization
CLAUDE.md
Use Codable for JSON serialization. Add explicit CodingKeys when API field names differ from Swift property names, and use decodeIfPresent for optional fields.
struct UserResponse: Codable {
let id: String
let displayName: String
let avatarUrl: String?
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
case avatarUrl = "avatar_url"
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(String.self, forKey: .id)
displayName = try c.decode(String.self, forKey: .displayName)
avatarUrl = try c.decodeIfPresent(String.self, forKey: .avatarUrl)
}
}
Never force-unwrap decoded values. Use decodeIfPresent or provide defaults for fields that might be absent.
Copy this block into your CLAUDE.md or agent config file to enforce it in your workflow.