SwiftMidMCQ
What is `Codable` and how does it work?
Test your knowledge:
Explanation & Code
Answer:
Codable is a type alias for Encodable & Decodable. It lets you convert Swift types to and from external formats like JSON with minimal boilerplate. The compiler auto-synthesizes the implementation if property names match the JSON keys.
Code Example:
struct User: Codable {
let id: Int
let name: String
let email: String
}
// Decoding JSON → Swift
let json = """
{ "id": 1, "name": "Alice", "email": "alice@example.com" }
""".data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: json)
print(user.name) // "Alice"
// Encoding Swift → JSON
let encoded = try JSONEncoder().encode(user)
// Custom key mapping
struct Article: Codable {
let title: String
let publishedAt: Date
enum CodingKeys: String, CodingKey {
case title
case publishedAt = "published_at" // maps snake_case to camelCase
}
}
Rate your understanding: