Skip to content

Instantly share code, notes, and snippets.

@robtimp
Created June 26, 2019 17:02
Show Gist options
  • Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.
Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.
Circular enum with example
protocol CircularEnum: CaseIterable where Self.AllCases.Element: Equatable {
var currentIndex: Self.AllCases.Index { get }
func next() -> Self.AllCases.Element
func previous() -> Self.AllCases.Element
}
extension CircularEnum {
var currentIndex: Self.AllCases.Index {
return Self.allCases.firstIndex(of: self)!
}
func next() -> Self.AllCases.Element {
let allCases = Self.allCases
let nextIndex = allCases.index(after: currentIndex)
if nextIndex == allCases.endIndex {
return allCases.first!
}
return allCases[nextIndex]
}
func previous() -> Self.AllCases.Element {
let allCases = Self.allCases
var index = currentIndex
if index == allCases.startIndex {
index = allCases.endIndex
}
index = allCases.index(index, offsetBy: -1)
return allCases[index]
}
}
enum Season: CircularEnum {
case winter
case spring
case summer
case fall
}
let season = Season.fall
season.previous() // summer
season.next() // winter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment