From 3d612417dcdf7a3328bcb9714fc6e4efb3c93f38 Mon Sep 17 00:00:00 2001 From: "Bruce, Matt R" Date: Thu, 22 Feb 2024 19:07:05 +0000 Subject: [PATCH] enum codable fix --- .../Atomic/Extensions/VDS-Enums+Codable.swift | 74 ++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/MVMCoreUI/Atomic/Extensions/VDS-Enums+Codable.swift b/MVMCoreUI/Atomic/Extensions/VDS-Enums+Codable.swift index 6a9cc598..8f184d5a 100644 --- a/MVMCoreUI/Atomic/Extensions/VDS-Enums+Codable.swift +++ b/MVMCoreUI/Atomic/Extensions/VDS-Enums+Codable.swift @@ -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 public typealias Surface = Wrapper } + +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) + } + } +}