Last active
August 5, 2020 13:12
Failable Codable initialiser for RawRepresentable types
This file contains 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
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