Declaring and using a bit field enum in Swift

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

    @Mattt's very famous "NSHipster" has an extensive detailed description of the RawOptionsSetType : http://nshipster.com/rawoptionsettype/

    It includes a handy Xcode snipped:

    struct <# Options #> : RawOptionSetType, BooleanType {
        private var value: UInt = 0
        init(_ value: UInt) { self.value = value }
        var boolValue: Bool { return value != 0 }
        static func fromMask(raw: UInt) -> <# Options #> { return self(raw) }
        static func fromRaw(raw: UInt) -> <# Options #>? { return self(raw) }
        func toRaw() -> UInt { return value }
        static var allZeros: <# Options #> { return self(0) }
        static func convertFromNilLiteral() -> <# Options #> { return self(0) }
    
        static var None: <# Options #>          { return self(0b0000) }
        static var <# Option #>: <# Options #>  { return self(0b0001) }
        // ...
    }
    

提交回复
热议问题