Skip to content

Instantly share code, notes, and snippets.

@robtimp
Created June 26, 2019 17:02
Show Gist options
  • Select an option

  • Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.

Select an option

Save robtimp/05b7dec6a2d5d9e707b23a2f04e52cc8 to your computer and use it in GitHub Desktop.

Revisions

  1. robtimp created this gist Jun 26, 2019.
    43 changes: 43 additions & 0 deletions CircularEnum.swift
    Original 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