Created
February 19, 2021 15:57
-
-
Save scottymac/4c85e24e5008d2bb0b57ced2fe1bfa61 to your computer and use it in GitHub Desktop.
Swift Toggleable Enum protocol extension
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
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