Closed AquaGeek closed 8 years ago
Enums can be made to conform to JSONDecodable
and JSONEncodable
like anything else:
enum MyRaw: String {
case Foo, Bar
}
extension MyRaw: JSONDecodable, JSONEncodable {
init(json: JSON) throws {
let string = try json.decode(type: String.self)
guard let value = MyRaw(rawValue: string) else {
throw JSON.Error.ValueNotConvertible(value: json, to: MyRaw.self)
}
self = value
}
func toJSON() -> JSON {
return rawValue.toJSON()
}
}
This would be great to do with a protocol extension:
extension RawRepresentable where RawValue: JSONDecodable {
init(json: JSON) throws {
let raw = try json.decode(type: RawValue.self)
guard let value = Self(rawValue: raw) else {
throw JSON.Error.ValueNotConvertible(value: json, to: Self.self)
}
self = value
}
}
extension RawRepresentable where RawValue: JSONEncodable {
func toJSON() -> JSON {
return rawValue.toJSON()
}
}
extension MyRaw: JSONDecodable, JSONEncodable {}
Which would be a great candidate for inclusion in the project. :wink:
Is anybody is using Freddy to parse types with enums and, if so, what is your approach? I have several models that contain enums with a string raw value.