Declaring and using a bit field enum in Swift

前端 未结 14 2031
余生分开走
余生分开走 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:47

    I think maybe some of the answers here are outdated with overcomplicated solutions? This works fine for me..

    enum MyEnum: Int  {
    
        case One = 0
        case Two = 1
        case Three = 2
        case Four = 4
        case Five = 8
        case Six = 16
    
    }
    
    let enumCombined = MyEnum.Five.rawValue | MyEnum.Six.rawValue
    
    if enumCombined & MyEnum.Six.rawValue != 0 {
        println("yay") // prints
    }
    
    if enumCombined & MyEnum.Five.rawValue != 0 {
        println("yay again") // prints
    }
    
    if enumCombined & MyEnum.Two.rawValue != 0 {
        println("shouldn't print") // doesn't print
    }
    

提交回复
热议问题