Codable combines Encodable and Decodable for serialization—JSON via JSONEncoder and JSONDecoder, similar to Gson in Java or System.Text.Json in C#.
Encoding and decoding
struct User: Codable {
let name: String
let score: Int
}
let user = User(name: "Ada", score: 98)
let data = try JSONEncoder().encode(user)
let decoded = try JSONDecoder().decode(User.self, from: data)
Custom keys and dates
Use CodingKeys enum for snake_case JSON; configure encoder dateEncodingStrategy for ISO-8601.
Important interview questions and answers
- Q: Codable vs manual JSON?
A: Codable is compile-time safe and maintainable; manual dictionaries suit dynamic schema-less payloads. - Q: Optional properties in JSON?
A: Missing keys decode to nil for optional properties; required properties throw decoding errors.
Self-check
- What protocol must types adopt for JSON encoding?
- What type converts JSON Data to Swift structs?
Tip: Use CodingKeys when JSON keys use snake_case and Swift properties use camelCase.
Interview prep
- Codable benefit?
Compile-time safe serialization vs manual dictionaries.
- Missing JSON keys?
Optional properties decode to nil; required properties throw.