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)
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?