Last active
July 2, 2024 09:04
-
-
Save ricardohochman/91f0b5c59ae9478e949e4784d9f87d43 to your computer and use it in GitHub Desktop.
Safely decode and encode enums in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public struct OptionalCodableEnum<T>: Codable where T: RawRepresentable, T.RawValue: Codable { | |
public let value: T? | |
public init(value: T) { | |
self.value = value | |
} | |
public init(from decoder: Decoder) throws { | |
value = T(rawValue: try decoder.singleValueContainer().decode(T.RawValue.self)) | |
} | |
public func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
try container.encode(value?.rawValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment