Created
July 13, 2021 12:50
-
-
Save darrarski/cef6bd3c30f4b5acb2d718f9db3e378d to your computer and use it in GitHub Desktop.
Swift `toggle()` 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out CaseSwitchable.swift as well