Skip to content

Instantly share code, notes, and snippets.

@darrarski
Created July 13, 2021 16:32
Show Gist options
  • Save darrarski/b86e51c84d4ea91e23b5cd2f197b2dea to your computer and use it in GitHub Desktop.
Save darrarski/b86e51c84d4ea91e23b5cd2f197b2dea to your computer and use it in GitHub Desktop.
Swift `switch()` and `next()` extension for enums
protocol CaseSwitchable: CaseIterable, Equatable {}
extension CaseSwitchable {
mutating func `switch`() {
self = next()
}
func next() -> Self {
self.next() ?? Self.allCases.first!
}
func next() -> Self? {
let index = Self.allCases.firstIndex(of: self)!
let nextIndex = Self.allCases.index(after: index)
guard nextIndex < Self.allCases.endIndex else {
return nil
}
return Self.allCases[nextIndex]
}
}
// MARK: - Example
enum MyEnum: CaseSwitchable {
case one
case two
case three
}
var value = MyEnum.one
value.switch() // → two
value.switch() // → three
value.switch() // → one
let next1: MyEnum = value.next() // → two
let next2: MyEnum = next1.next() // → three
let next3: MyEnum = next2.next() // → one
let optionalNext1: MyEnum? = value.next() // → two
let optionalNext2: MyEnum? = next1.next() // → three
let optionalNext3: MyEnum? = next2.next() // → nil
@darrarski
Copy link
Author

Screenshot 2021-07-13 at 18 06 08

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment