Skip to content

Instantly share code, notes, and snippets.

@ricardohochman
Last active July 2, 2024 09:04
Show Gist options
  • Save ricardohochman/91f0b5c59ae9478e949e4784d9f87d43 to your computer and use it in GitHub Desktop.
Save ricardohochman/91f0b5c59ae9478e949e4784d9f87d43 to your computer and use it in GitHub Desktop.
Safely decode and encode enums in Swift
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