Skip to content

Instantly share code, notes, and snippets.

@enebin
Created November 13, 2023 10:38
Show Gist options
  • Save enebin/d941c1dacb85a46a7d6592da20b93437 to your computer and use it in GitHub Desktop.
Save enebin/d941c1dacb85a46a7d6592da20b93437 to your computer and use it in GitHub Desktop.
extension CaseIterable where Self: Equatable, AllCases: BidirectionalCollection {
func previous() -> Self {
let all = Self.allCases
let idx = all.firstIndex(of: self)!
let previous = all.index(before: idx)
if idx == all.startIndex {
return self
} else {
return all[previous]
}
}
func next() -> Self {
let all = Self.allCases
let idx = all.firstIndex(of: self)!
let next = all.index(after: idx)
if next == all.endIndex {
return self
} else {
return all[next]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment