🍎 Swift & iOS Intermediate

What is Codable in Swift?

Answer

Codable is a type alias for the combined Encodable & Decodable protocols. It enables automatic JSON serialization and deserialization with minimal boilerplate — the compiler synthesizes the implementation automatically for types with Codable properties. Basic Codable: struct User: Codable { let id: Int let name: String let email: String let joinDate: Date } // Decode JSON: let json = """{"id":1,"name":"Alice","email":"alice@example.com","joinDate":"2024-01-15T10:00:00Z"}""" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let user = try decoder.decode(User.self, from: json.data(using: .utf8)!) // Encode to JSON: let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(user) let jsonString = String(data: data, encoding: .utf8)!. Custom key mapping (CodingKeys): struct Product: Codable { let productID: Int let productName: String enum CodingKeys: String, CodingKey { case productID = "product_id" // JSON uses snake_case case productName = "product_name" } }. Nested types: struct Order: Codable { let id: Int let items: [OrderItem] // Nested Codable struct let address: Address }. Custom encoding/decoding: implement encode(to:) and init(from:) for complex types. keyDecodingStrategy (snake_case): decoder.keyDecodingStrategy = .convertFromSnakeCase // "user_name" -> userName. Codable replaces hand-written JSON parsing and third-party libraries like SwiftyJSON for most use cases.