Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

darrarski commented Jul 13, 2021

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