Search code examples
objective-cswiftbit-fields

Objective-C NS_OPTIONS in Swift


I'm given an NS_OPTIONS defined in Objective-C:

typedef NS_OPTIONS(NSInteger, MyType) {
   MyTypeOption1 = 1 << 0,
   MyTypeOption2 = 1 << 1,
   MyTypeOption3 = 1 << 2,
   // etc
}

I'm importing this type into Swift, but I can't form bit fields.

let default : MyType = MyTypeOption1 | MyTypeOption2

The error:

Protocol 'BinaryInteger' requires that 'MyType' conform to 'BinaryInteger'

The IDE indicates that it is the standing-colon bitwise-or operator which is the problem.

Altering the NS_OPTIONS declarations or declaring a new type with Swift's OptionSet aren't ... options. How can I get Swift to play ball?


Solution

  • Your syntax is simply wrong. The Swift syntax for a bit field (which is actually called an OptionSet in Swift) is the array syntax, not the bitwise OR syntax.

    Objective-C enums created using NS_OPTIONS are automatically imported into Swift as OptionSets.

    So you just need to do let default: MyType = [.option1, .option2] instead of trying to replicate the Obj-C bitfield syntax.

    For more info on the topic, see How to create NS_OPTIONS-style bitmask enumerations in Swift?