bignerdranch / Freddy

A reusable framework for parsing JSON in Swift.
MIT License
1.09k stars 119 forks source link

Enum decoding? #139

Closed AquaGeek closed 8 years ago

AquaGeek commented 8 years ago

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.

zwaldowski commented 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: