Skip to content

Instantly share code, notes, and snippets.

@darrarski
Created July 13, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrarski/cef6bd3c30f4b5acb2d718f9db3e378d to your computer and use it in GitHub Desktop.
Save darrarski/cef6bd3c30f4b5acb2d718f9db3e378d to your computer and use it in GitHub Desktop.
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

Check out CaseSwitchable.swift as well

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