Closed mariotaku closed 8 years ago
Swift won't let use JSONDecodable with extension on classes
Can you clarify what you mean by this?
@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.
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.
Okay, I'll reopen this when I found better use case.
Swift won't let use JSONDecodable with extension on classes, added protocol can work around this issue.
Limitations: only works on final class