Switching Enum var mode
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
0
source to share
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)
Simon
+3
source to share
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
+1
source to share