使用可数的闭合范围作为枚举案例

时间:2017-09-24 16:42:58

标签: swift enums

我想使用一系列范围作为枚举案例

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
}

并且我不确定它是否可能,目前我得到了:

  

错误:枚举案例的原始值必须是文字       case lateNight = 0 ... 2

谢谢你看看! :)

1 个答案:

答案 0 :(得分:3)

我无法直接看到如何做到这一点。您可以将范围作为关联值放入每个枚举中,但这很快就会变得难看。

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()
    }
  }
}