Updated September 30 for Swift 1.1b3 compatibility.
Swift has an great enumeration type built in, so it isn’t surprising that NS_ENUM
-style enumerations are automatically bridged from Objective-C and similar ones are easy to create by hand. NS_OPTIONS
-style bitmasks, on the other hand, are a little harder to create for yourself. I looked through the bitmask options that Swift imports from Objective-C (UIViewAutoresizing
, for example), and found that options are declared as a struct
that conforms to protocol RawOptionSetType
, which in turn conforms to _RawOptionSetType
, Equatable
, RawRepresentable
, BitwiseOperationsType
, and NilLiteralConvertible
.
It’s a bit of a mess to write out, with a lot of repetition, so I’ve created a generator for NS_OPTIONS
bitmasks in Swift. Just enter the name of your options type and the list of options, then copy the customized code!
Note: As of beta 6, RawOptionSetType
no longer implements BooleanType
by default, so standard bitmask checks (if opt & .Option {...
) only work if you add BooleanType
protocol conformance manually.
struct MyOptions : RawOptionSetType {
typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
init(rawValue value: UInt) { self.value = value }
init(nilLiteral: ()) { self.value = 0 }
static var allZeros: MyOptions { return self(0) }
static func fromMask(raw: UInt) -> MyOptions { return self(raw) }
var rawValue: UInt { return self.value }
static var None: MyOptions { return self(0) }
static var Option: MyOptions { return self(1 << 0) }
}
Please let me know if you find this useful!