-
-
Notifications
You must be signed in to change notification settings - Fork 194
Closed
Labels
Description
I have a Day type:
enum Day: Int {
case Sunday = 0
case Monday = 1
case Tuesday = 2
case Wednesday = 3
case Thursday = 4
case Friday = 5
case Saturday = 6
static let Weekdays: [Day] = [.Monday, .Tuesday, .Wednesday, .Thursday, .Friday]
static let Weekends: [Day] = [.Saturday, .Sunday]
static let Daily: [Day] = Weekdays + Weekends
}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 of Days coming back with string values. I came up with a decode that can convert an array of strings into an array of Days, which is gross:
static func decodeFromStrings(strings: [String]) -> Decoded<[Day]> {
let ints = strings.flatMap { Int($0) }
if ints.count != strings.count {
return .customError("Could not convert all Strings to Ints for [Day].")
}
let days = ints.flatMap { Day(rawValue: $0) }
if days.count != strings.count {
return .customError("Could not convert all Ints to Days for [Day].")
}
return pure(days)
}Which I call like this:
<*> (j <|| ["key1", "key2", "day"] >>- Day.decodeFromStrings)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?