Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring and using a bit field enum in Swift

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 MyEnum: Int {     case One =      0x01     case Two =      0x02     case Four =     0x04     case Eight =    0x08 }  // This works as expected let m1: MyEnum = .One  // Compiler error: "Could not find an overload for '|' that accepts the supplied arguments" let combined: MyEnum = MyEnum.One | MyEnum.Four 

I looked at how Swift imports Foundation enum types, and it does so by defining a struct that conforms to the RawOptionSet protocol:

struct NSCalendarUnit : RawOptionSet {     init(_ value: UInt)     var value: UInt     static var CalendarUnitEra: NSCalendarUnit { get }     static var CalendarUnitYear: NSCalendarUnit { get }     // ... } 

And the RawOptionSet protocol is:

protocol RawOptionSet : LogicValue, Equatable {     class func fromMask(raw: Self.RawType) -> Self } 

However, there is no documentation on this protocol and I can't figure out how to implement it myself. Moreover, it's not clear if this is the official Swift way of implementing bit fields or if this is only how the Objective-C bridge represents them.

like image 231
Pascal Bourque Avatar asked Jun 09 '14 00:06

Pascal Bourque


People also ask

What is a bit field enum?

A standard enumeration provides a list of named integer values. These values can be accessed using either the name or the associated value. Using the name rather than the value from within your program makes the code much easier to read and maintain.

How do I enum in Swift?

In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.

What is difference between enum and enumeration in Swift?

Enumeration is a data type that allows you to define a list of possible values. An enum allows you to create a data type with those set of values so that they can be recognised consistently throughout your app.

Why do we use enum in Swift?

Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.


1 Answers

You can build a struct that conforms to the RawOptionSet protocol, and you'll be able to use it like the built-in enum type but with bitmask functionality as well. The answer here shows how: Swift NS_OPTIONS-style bitmask enumerations.

like image 89
Nate Cook Avatar answered Oct 06 '22 19:10

Nate Cook