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)
}
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?