Declaring and using a bit field enum in Swift

前端 未结 14 1992
余生分开走
余生分开走 2020-12-13 09:24

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         


        
相关标签:
14条回答
  • 2020-12-13 09:54

    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.

    0 讨论(0)
  • 2020-12-13 09:56

    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
    
    0 讨论(0)
提交回复
热议问题