Created
June 26, 2019 17:02
-
-
Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.
Circular enum with example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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