Created
June 26, 2019 17:02
-
-
Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.
Revisions
-
robtimp created this gist
Jun 26, 2019 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,43 @@ 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