Skip to content

Instantly share code, notes, and snippets.

@Sajjon
Created May 4, 2019 13:47
Show Gist options
  • Select an option

  • Save Sajjon/e7e8b6ca5a2281d3bf2daf1f86883d9f to your computer and use it in GitHub Desktop.

Select an option

Save Sajjon/e7e8b6ca5a2281d3bf2daf1f86883d9f to your computer and use it in GitHub Desktop.
Season from Month
enum Month: Int, CaseIterable {
case jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
}
extension Month {
var season: Season {
return Season(month: self)
}
}
enum Season: Int, CaseIterable {
case winter, spring, summer, autumn
}
extension Season {
init(month: Month) {
let seasonIndex = ((month.rawValue + 1 ) / (Month.count / Season.count)) % Season.count
guard let season = Season(rawValue: seasonIndex) else {
fatalError("Incorrect implementation of `seasonIndex` (was: \(seasonIndex)) and/or rawValue of 'Season'")
}
self = season
}
}
extension CaseIterable {
static var count: Int { return Self.allCases.count }
}
for month in Month.allCases {
print("\(month) is \(month.season)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment