Last active
May 18, 2022 17:39
-
-
Save abesmon/6178d3847fa98b91b55cb39cc6be5d5b to your computer and use it in GitHub Desktop.
codable property wrapper
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
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