first cut for fixing issue with codable for complex enums

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2024-02-22 12:13:36 -06:00
parent 3eaf765655
commit 673cf69e20

View File

@ -25,8 +25,6 @@ extension VDS.Tabs.Overflow: Codable {}
extension VDS.Tabs.Size: Codable {}
extension VDS.TextLink.Size: Codable {}
extension VDS.TextLinkCaret.IconPosition: Codable {}
extension VDS.TileContainer.BackgroundColor: Codable {}
extension VDS.TileContainer.Padding: Codable {}
extension VDS.TileContainer.AspectRatio: Codable {}
extension VDS.Tooltip.FillColor: Codable {}
extension VDS.Tooltip.Size: Codable {}
@ -61,3 +59,75 @@ extension DecodableDefault {
public typealias BlackColor = Wrapper<Sources.BlackColor>
public typealias Surface = Wrapper<Sources.Surface>
}
extension VDS.TileContainer.BackgroundColor: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .custom(let value):
try container.encode(value)
default:
try container.encode(String(reflecting: self))
}
}
// Init from decoder to handle the decoding based on the type
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let type = try container.decode(String.self)
switch type {
case "primary":
self = .primary
case "secondary":
self = .secondary
case "white":
self = .white
case "black":
self = .black
default:
self = .custom(type)
}
}
}
extension VDS.TileContainer.Padding: Codable {
enum PaddingError: Error {
case valueNotFound(type: String)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .custom(let value):
try container.encode(value)
default:
try container.encode(String(reflecting: self))
}
}
// Init from decoder to handle the decoding based on the type
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
let type = try container.decode(String.self)
switch type {
case "padding2X":
self = .padding2X
case "padding4X":
self = .padding4X
case "padding6X":
self = .padding6X
case "padding8X":
self = .padding8X
case "padding12X":
self = .padding12X
default:
throw PaddingError.valueNotFound(type: type)
}
} catch PaddingError.valueNotFound(let type) {
throw PaddingError.valueNotFound(type: type)
} catch {
let type = try container.decode(CGFloat.self)
self = .custom(type)
}
}
}