In Apple's documentation about interacting with C APIs, they describe the way NS_ENUM
-marked C-style enumerations are imported as Swift enumerations. This makes sense, and since enumerations in Swift are readily provided as the enum
value type it's easy to see how to create our own.
Further down, it says this about NS_OPTIONS
-marked C-style options:
Swift also imports options marked with the
NS_OPTIONS
macro. Whereas options behave similarly to imported enumerations, options can also support some bitwise operations, such as&
,|
, and~
. In Objective-C, you represent an empty option set with the constant zero (0
). In Swift, usenil
to represent the absence of any options.
Given that there isn't an options
value type in Swift, how can we create a C-Style options variable to work with?
Swift 2.0 example from the documentation:
You can find it here
As Rickster already mentioned, you can use OptionSetType in Swift 2.0. NS_OPTIONS types get imported as conforming to the
OptionSetType
protocol, which presents a set-like interface for options:It gives you this way of working:
I use the following I need the both values I can get, rawValue for indexing arrays and value for flags.
And if one needs more just add a computed property.
In order to avoid hard coding the bit positions, which is unavoidable when using
(1 << 0)
,(1 << 1)
,(1 << 15)
etc. or even worse1
,2
,16384
etc. or some hexadecimal variation, one could first defines the bits in anenum
, then let said enum do the bit ordinal calculation:In Swift 2 (currently beta as part of the Xcode 7 beta),
NS_OPTIONS
-style types are imported as subtypes of the newOptionSetType
type. And thanks to the new Protocol Extensions feature and the wayOptionSetType
is implemented in the standard library, you can declare your own types that extendOptionsSetType
and get all the same functions and methods that importedNS_OPTIONS
-style types get.But those functions aren't based on bitwise arithmetic operators anymore. That working with a set of non-exclusive Boolean options in C requires masking and twiddling bits in a field is an implementation detail. Really, a set of options is a set... a collection of unique items. So
OptionsSetType
gets all the methods from theSetAlgebraType
protocol, like creation from array literal syntax, queries likecontains
, masking withintersection
, etc. (No more having to remember which funny character to use for which membership test!)Xcode 6.1 Beta 2 brought some changes to the
RawOptionSetType
protocol (see this Airspeedvelocity blog entry and the Apple release notes).Based on Nate Cooks example here is an updated solution. You can define your own option set like this:
It can then be used like this to define variables:
And like this to test for bits: