Skip to content

Instantly share code, notes, and snippets.

@robtimp
Last active December 7, 2018 21:10
Show Gist options
  • Save robtimp/478b87307f8792458210f7e555c47d96 to your computer and use it in GitHub Desktop.
Save robtimp/478b87307f8792458210f7e555c47d96 to your computer and use it in GitHub Desktop.
CaseIterable non-optional index
enum NoteLetter: CaseIterable {
case c
case d
case e
case f
case g
case a
case b
}
extension CaseIterable where Self: Equatable {
static var count: Int {
return Self.allCases.count
}
static func index(of item: Self) -> AllCases.Index {
return allCases.firstIndex(of: item)!
}
static func element(atIndex index: AllCases.Index) -> Self {
return allCases[index]
}
}
NoteLetter.element(atIndex: 3) // NoteLetter.f
NoteLetter.count // 7
NoteLetter.index(of: .a) // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment