I would like to use a series of ranges as enum cases
enum TimeOfDay: CountableClosedRange<Int> {
case lateNight = 0...2
case earlyMorning = 3...6
case morning = 7...11
case afternoon = 12...17
case evening = 18...20
case night = 21...24
}
and am not sure if it's possible, currently I get:
error: raw value for enum case must be a literal case lateNight = 0...2
Thanks for taking a look! :)
I can't see how to do this directly. You could put the ranges into each enumeration as an associated value but that gets ugly quickly.
enum TimeOfDay {
case lateNight
case earlyMorning
case morning
case afternoon
case evening
case night
var range: CountableClosedRange<Int> {
switch self {
case .lateNight: return 0...2
case .earlyMorning: return 3...6
case .morning: return 7...11
case .afternoon: return 12...17
case .evening: return 18...20
case .night: return 21...23
}
}
init(_ hour: Int) {
switch (hour % 24) {
case TimeOfDay.lateNight.range: self = .lateNight
case TimeOfDay.earlyMorning.range: self = .earlyMorning
case TimeOfDay.morning.range: self = .morning
case TimeOfDay.afternoon.range: self = .afternoon
case TimeOfDay.evening.range: self = .evening
case TimeOfDay.night.range: self = .night
default: fatalError()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With