You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
26 lines
726 B
26 lines
726 B
internal struct CodableEnum<E: CaseIterable & CodingKey>: Codable {
|
|
public let variant: E
|
|
|
|
init(of variant: E) {
|
|
self.variant = variant
|
|
}
|
|
|
|
init(from decoder: any Decoder) throws {
|
|
let container = try decoder.singleValueContainer()
|
|
let name = try container.decode(String.self)
|
|
|
|
guard let variant = E.allCases.first(where: { variant in
|
|
variant.stringValue == name
|
|
}) else {
|
|
throw DeError.InvalidVariant
|
|
}
|
|
|
|
self.variant = variant
|
|
}
|
|
|
|
func encode(to encoder: any Encoder) throws {
|
|
var container = encoder.singleValueContainer()
|
|
try container.encode(self.variant.stringValue)
|
|
}
|
|
}
|