Skip to content

Instantly share code, notes, and snippets.

@scottymac
Created February 19, 2021 15:57
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 scottymac/4c85e24e5008d2bb0b57ced2fe1bfa61 to your computer and use it in GitHub Desktop.
Save scottymac/4c85e24e5008d2bb0b57ced2fe1bfa61 to your computer and use it in GitHub Desktop.
Swift Toggleable Enum protocol extension
import Foundation
protocol Toggleable: CaseIterable, Equatable {
mutating func toggle()
}
extension Toggleable {
mutating func toggle() {
guard Self.allCases.count == 2, let firstCase = Self.allCases.first else {
fatalError("Enum must have only two elements")
}
if self == firstCase {
self = Self.allCases[1 as! Self.AllCases.Index]
} else {
self = firstCase
}
}
}
enum TestEnum: Toggleable {
case expanded, collapsed
}
var test = TestEnum.expanded
test.toggle()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment