Anviking / Decodable

[Probably deprecated] Swift 2/3 JSON unmarshalling done (more) right
MIT License
1.04k stars 73 forks source link

Does Decodable only work with structs? #37

Closed kylebshr closed 9 years ago

kylebshr commented 9 years ago

I'm trying to use Decodable to create Realm objects, but I'm having issues. Then I realized all the examples were structs — does Decodable not work with classes?

Anviking commented 9 years ago

It wasn't designed for it, but yes it should work. Some problems though:

The latter should not be a problem though if you have default values on your Realm object.

Have you seen the NSDate-example?

public class func decode(json: AnyObject) throws -> Self {
        let string = try String.decode(json)

        guard let date = ISO8601DateFormatter.dateFromString(string) else {
            throw NSDateDecodingError.InvalidStringFormat
        }

        return self.init(timeIntervalSince1970: date.timeIntervalSince1970)
}
kylebshr commented 9 years ago

With the NSDate example — if I needed multiple properties, I would have to decode them all, right?

Here's what I have set up right now, and it's obviously not working. Am I just completely wrong about how it can be used? My knowledge of protocols and the way types work here is not very strong. Returning Self Returning Test

Anviking commented 9 years ago

What if you do return try self.init instead of return try Test?

kylebshr commented 9 years ago

No luck :( screen shot 2015-10-01 at 4 20 01 pm

Anviking commented 9 years ago

And if you also make the initializer required? skarmavbild 2015-10-01 kl 22 27 22

kylebshr commented 9 years ago

Oh wow, I didn't know you could do that — I should read up on my initializers. This seems like it should work great, thank you! Do you see any possible drawbacks or issues doing this?

Anviking commented 9 years ago

I guess it might be bad if you subclass a lot. Perhaps this is a little bit better: skarmavbild 2015-10-01 kl 22 34 02

kylebshr commented 9 years ago

Much better, almost half the code. Thank you!

Sent from my iPhone

On Oct 1, 2015, at 4:36 PM, Johannes Lund notifications@github.com wrote:

I guess it might be bad if you subclass a lot. Perhaps this is a little bit better:

— Reply to this email directly or view it on GitHub.