Swift `switch()` and `next()` extension for enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
darrarski commentedJul 13, 2021