bignerdranch / Freddy

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

Supports JSONStaticDecodable #227

Closed mariotaku closed 8 years ago

mariotaku commented 8 years ago

Swift won't let use JSONDecodable with extension on classes, added protocol can work around this issue.

Limitations: only works on final class

zwaldowski commented 8 years ago

Swift won't let use JSONDecodable with extension on classes

Can you clarify what you mean by this?

mariotaku commented 8 years ago

@zwaldowski For a example

public final class PersonClass: CustomStringConvertible {
    public enum EyeColor: String {
        case Brown = "brown"
        case Blue = "blue"
        case Green = "green"
    }

    public let name: String
    public var age: Int
    public let eyeColor: EyeColor
    public let spouse: Bool

    init(name: String, age: Int, eyeColor: EyeColor, spouse: Bool) {
        self.name = name
        self.age = age
        self.eyeColor = eyeColor
        self.spouse = spouse
    }

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

You can't write extension for this class conforming JSONDecodable, but with JSONStaticDecodable, you can easily do so.

zwaldowski commented 8 years ago

This is behavior is intended with the way Swift initializers work. I don't understand.


public class PersonClass_InlineConformance: CustomStringConvertible, JSONDecodable {

    public enum EyeColor: String, JSONDecodable {
        case Brown = "brown"
        case Blue = "blue"
        case Green = "green"
    }

    public let name: String
    public var age: Int
    public let eyeColor: EyeColor
    public let spouse: Bool

    init(name: String, age: Int, eyeColor: EyeColor, spouse: Bool) {
        self.name = name
        self.age = age
        self.eyeColor = eyeColor
        self.spouse = spouse
    }

    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }

    public required init(json: JSON) throws {
        self.name = try json.getString(at: "name")
        self.age = try json.getInt(at: "age")
        self.eyeColor = try json.decode(at: "eyeColor")
        self.spouse = try json.getBool(at: "spuse")
    }
}

I don't think we are interested in adding a slightly alternate API.

mariotaku commented 8 years ago

Okay, I'll reopen this when I found better use case.