-
-
Notifications
You must be signed in to change notification settings - Fork 198
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
Using an alternate decode for an array of enums #284
Comments
Fantastic question, this is something we should add documentation about.
Essentially, you'd end up with something like this: <*> (j <|| ["key1", "key2", "day"]) <|> (j <|| ["key1", "key2", "day"] >>- Day.decodeFromStrings) So it'll try to decode from You might even go further and abstract out a couple helper methods: func decodeDays<T: Decodable where T.DecodedType == T>(j: JSON) -> [T] {
return j <|| ["key1", "key2", "day"]
}
func decodeStringDays(j: JSON) -> Decoded<[Day]> {
return decodeDays(j) >>- Day.decodeFromStrings
} Then your parser would be simplified a bit: <*> decodeDays(j) <|> decodeStringDays(j) |
Just an FYI, weekdays/weekends are not statically defined; they vary based on locales. |
While true, that is completely irrelevant to the discussion about Argo's |
@owensd They're static in this API, as there is no localization at all. That is just the tip of the iceberg of bad practice for this API. @gfontenot Thanks for the information, but I think I was clear. The endpoint that returns the ints as strings is completely separate from the one that properly returns them as ints, so there's no use for the alternate operator. My question was more about the appropriate syntax to pull a array of an enum from an array of strings while calling a custom decode function that doesn't operate at an array level. If you think my current solution is okay, that's fine, I just thought there might be a better way I hadn't figured out. |
I might override the static func decode(j: JSON) -> Decoded<Day> {
switch j {
case .String(s): // convert to int and pass into rawType constructor
case .Number(n): // try to pass into rawType constructor (cast as Int)
default: .typeMismatch ...
}
} |
@tonyd256 Thanks. I had wanted to keep the automatic |
I have a
Day
type:Works great, gets the automatic decode from the
RawRepresentable
extension. However, in the same API, days are sometimes represented as strings (e.g."1"
) rather than the raw ints that get decoded automatically. Obviously I have to make a new decode function, but I'm unsure how to apply when decoding an array ofDay
s coming back with string values. I came up with a decode that can convert an array of strings into an array ofDay
s, which is gross:Which I call like this:
Creating a
decode
variant that turns strings into ints and then decodes the enum is easy, but how would I call this function on the array of strings I get when parsing?The text was updated successfully, but these errors were encountered: