Skip to content

Instantly share code, notes, and snippets.

@alfavata
Last active August 5, 2020 13:12
Show Gist options
  • Save alfavata/584ac76520c635bf98e76e4a7b2392e0 to your computer and use it in GitHub Desktop.
Save alfavata/584ac76520c635bf98e76e4a7b2392e0 to your computer and use it in GitHub Desktop.
Failable Codable initialiser for RawRepresentable types
extension RawRepresentable where RawValue: Decodable {
init?(from decoder: Decoder) throws {
self.init(rawValue: try decoder.singleValueContainer().decode(RawValue.self))
}
}
enum Enum: String, Codable {
case aValidCase, anotherValidCase, unknown
init(from decoder: Decoder) throws {
self = try Enum(from: decoder) ?? .unknown
}
}
struct Struct: Codable {
let property: Enum
}
let json = """
{
"property": "anInvalidCase"
}
"""
do {
let s = try JSONDecoder().decode(Struct.self, from: Data(json.utf8))
print(String(describing: s.property.rawValue))
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment