Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function that takes multiple Decodable classes/structs and returns the first to decode #84

Merged
merged 8 commits into from
Apr 12, 2016

Conversation

Qata
Copy link
Contributor

@Qata Qata commented Apr 6, 2016

Inspired heavily by the Elm JSON.Decode function oneOf

@Qata
Copy link
Contributor Author

Qata commented Apr 6, 2016

The variadic list is so that lists of zero length cannot be passed in, preventing runtime errors that you would otherwise bring in with assert(objectTypes.count > 0)

@Anviking
Copy link
Owner

Hi, thanks for addressing and sorry for late response, but wouldn't callers always have to force-downcast the result in all circumstances?

In that case, although

decodeAsOneOf(json, objectTypes: Car.self, Bus.self, ...) as! Vehicle

may be prettier (and slightly different?) than

(try? Car.decode(json) as Vehicle) ?? Bus.decode(json) as Vehicle ...

, I don't like that a type could not conform to Vehicle and risk not being discovered.

@Qata
Copy link
Contributor Author

Qata commented Apr 11, 2016

In my code I've been using optional downcasting, usually with flatMapping since in the JSON I've been working with, this kind of decoding is really helpful with arrays of dictionaries where the data is essentially unofficially subtyped.

@Anviking
Copy link
Owner

Ah, right, didn't think of that. Hopefully future versions of Swift will allow a more constrained version though. Could you add a short test case, mainly for adequate example-usage in a new file?

@Qata
Copy link
Contributor Author

Qata commented Apr 11, 2016

In a completely new file or in an existing test file?

@Anviking
Copy link
Owner

I would say new, like DecodeAsOneOfTests or something.

@Qata
Copy link
Contributor Author

Qata commented Apr 12, 2016

Ugh, Travis is on an old version of Xcode. The tests I committed are building fine in 7.3.

@Anviking
Copy link
Owner

Thank you very much! And sorry about travis, will fix at some point.

@Anviking Anviking merged commit ffd7fad into Anviking:master Apr 12, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants