How do I map enums with associated values to Codable?

Here's how to map enums with associated values to Codable in Swift:

In Swift, you can use associated values with enums, but when you want to encode and decode them using Codable, you need to implement Encodable and Decodable protocols manually for your enum. Below is an example demonstrating how to do this:

enum Vehicle: Codable { case car(make: String, model: String) case bike(brand: String) case bus(seats: Int) enum CodingKeys: String, CodingKey { case type case make case model case brand case seats } enum VehicleType: String, Codable { case car case bike case bus } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(VehicleType.self, forKey: .type) switch type { case .car: let make = try container.decode(String.self, forKey: .make) let model = try container.decode(String.self, forKey: .model) self = .car(make: make, model: model) case .bike: let brand = try container.decode(String.self, forKey: .brand) self = .bike(brand: brand) case .bus: let seats = try container.decode(Int.self, forKey: .seats) self = .bus(seats: seats) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .car(let make, let model): try container.encode(VehicleType.car, forKey: .type) try container.encode(make, forKey: .make) try container.encode(model, forKey: .model) case .bike(let brand): try container.encode(VehicleType.bike, forKey: .type) try container.encode(brand, forKey: .brand) case .bus(let seats): try container.encode(VehicleType.bus, forKey: .type) try container.encode(seats, forKey: .seats) } } }

Swift Codable Enum Associated Values