Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a countable closed range as an enum case

Tags:

enums

swift

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! :)

like image 224
Fred Faust Avatar asked Sep 24 '17 16:09

Fred Faust


1 Answers

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()
    }
  }
}
like image 171
Price Ringo Avatar answered Sep 29 '22 06:09

Price Ringo