How do I use Codable with enums and associated values?

To use Codable with enums that have associated values in Swift, you need to implement the Codable protocol for the enum and handle the encoding and decoding of its associated values manually.

Here's a simple example demonstrating how to work with a Codable enum that has associated values:

import Foundation enum Vehicle: Codable { case car(brand: String, year: Int) case bike(type: String) private enum CodingKeys: String, CodingKey { case type case brand case year case bikeType = "type" } private enum VehicleType: String, Codable { case car case bike } 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 brand = try container.decode(String.self, forKey: .brand) let year = try container.decode(Int.self, forKey: .year) self = .car(brand: brand, year: year) case .bike: let bikeType = try container.decode(String.self, forKey: .bikeType) self = .bike(type: bikeType) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .car(let brand, let year): try container.encode(VehicleType.car, forKey: .type) try container.encode(brand, forKey: .brand) try container.encode(year, forKey: .year) case .bike(let type): try container.encode(VehicleType.bike, forKey: .type) try container.encode(type, forKey: .bikeType) } } } // Example usage let car = Vehicle.car(brand: "Toyota", year: 2020) let bike = Vehicle.bike(type: "Mountain") let encoder = JSONEncoder() let decoder = JSONDecoder() // Encoding if let encodedCar = try? encoder.encode(car), let decodedCar = try? decoder.decode(Vehicle.self, from: encodedCar) { print(decodedCar) } // Encoding if let encodedBike = try? encoder.encode(bike), let decodedBike = try? decoder.decode(Vehicle.self, from: encodedBike) { print(decodedBike) }

Swift Codable Enums Associated Values JSON Encoding JSON Decoding