Switching Enum var mode

What's the best way to flip between the state of an Enum?

enum EVEN_ODD { case Even, Odd }
var __mode_bit = EVEN_ODD.Even;

for _ in 1...5 {
    __mode_bit = (__mode_bit == .Even) ? .Odd : .Even


Can it be simplified __mode_bit?:



source to share

3 answers

Enumerations can have! the operator is implemented for them.

enum Parity { case Even, Odd }
prefix func !(a: Parity) -> Parity {
    return a == .Even ? .Odd : .Even


Now I can write like

var parity_mode = Parity.Even
parity_mode = !parity_mode // .Odd


Based on @Simon Gladman answer with Boolean reference



Take a look at Apple's documentation on Booleans, they give an example of a boolean typed enum: https://developer.apple.com/swift/blog/?id=8

Since you can create an enum from raw, you can switch the value to:

let true = MyBool(rawValue: false)





My preference would be to have the enum match _Incrementable

(which is underlined for some reason, although it seems like a reasonable non-internal protocol to me) and wrap it up.

enum EvenOdd {
    case Even, Odd

extension EvenOdd: _Incrementable {
    func successor() -> EvenOdd {
        return self == .Even ? .Odd : .Even

EvenOdd.Odd.successor()  // == .Even


This also gives you a free pre / post increment operator:

var bit = EvenOdd.Odd

++bit  // bit now Even
++bit  // bit now Odd
++bit  // bit now Even etc




All Articles