How should bit fields be declared and used in Swift?
Declaring an enum like this does work, but trying to OR 2 values together fails to compile:
enum
They showed how to do this in one of the WWDC videos.
let combined = MyEnum.One.toRaw() | MyEnum.Four.toRaw()
Note that combined
will be Int
type and will actually get a compiler error if you specify let combined: MyEnum
. That is because there is no enum value for 0x05
which is the result of the expression.
I use the following I need the both values I can get, rawValue for indexing arrays and value for flags.
enum MyEnum: Int {
case one
case two
case four
case eight
var value: UInt8 {
return UInt8(1 << self.rawValue)
}
}
let flags: UInt8 = MyEnum.one.value ^ MyEnum.eight.value
(flags & MyEnum.eight.value) > 0 // true
(flags & MyEnum.four.value) > 0 // false
(flags & MyEnum.two.value) > 0 // false
(flags & MyEnum.one.value) > 0 // true
MyEnum.eight.rawValue // 3
MyEnum.four.rawValue // 2