Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift `toggle()` extension for enums
protocol CaseTogglable {}
extension CaseTogglable where Self: CaseIterable, Self: Equatable {
mutating func toggle() {
assert(Self.allCases.isEmpty == false, "CaseTogglable cannot be applied to an enum with no cases!")
let index = Self.allCases.firstIndex(of: self)!
let nextIndex = Self.allCases.index(after: index)
if nextIndex < Self.allCases.endIndex {
self = Self.allCases[nextIndex]
} else {
self = Self.allCases[Self.allCases.startIndex]
}
}
func toggled() -> Self {
var copy = self
copy.toggle()
return copy
}
}
// MARK: - Example
enum MyEnum: CaseIterable, CaseTogglable {
case one
case two
case three
}
var value = MyEnum.one
value.toggle() // → two
value.toggle() // → three
value.toggle() // → one
let toggled1 = value.toggled() // → two
let toggled2 = toggled1.toggled() // → three
let toggled3 = toggled2.toggled() // → one
@darrarski
Copy link
Author

darrarski commented Jul 13, 2021

Screenshot 2021-07-13 at 14 49 08

@darrarski
Copy link
Author

darrarski commented Jul 13, 2021

Check out CaseSwitchable.swift as well

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