Skip to content

Instantly share code, notes, and snippets.

@abesmon
Last active May 18, 2022 17:39
Show Gist options
  • Save abesmon/6178d3847fa98b91b55cb39cc6be5d5b to your computer and use it in GitHub Desktop.
Save abesmon/6178d3847fa98b91b55cb39cc6be5d5b to your computer and use it in GitHub Desktop.
codable property wrapper
import UIKit
@propertyWrapper
struct CodableEnum<T: RawRepresentable>: Codable where T.RawValue: Codable {
private var value: T.RawValue
var wrappedValue: T {
get { T(rawValue: value)! }
set { value = newValue.rawValue }
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(T.RawValue.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment