From the author of

Option sets received a welcome facelift in Swift 2.0. Lightweight sets of Boolean values, option sets enable you to store and query independent flags. Swift treats these as a collection of orthogonal settable switches. Now, you just build sets using simple, readable constructs, and then add and remove and test members as needed.

You do all this using almost no low-level bitwise operation programming. Option sets are easier to use than before, and the code you work with is more readable and maintainable than ever. Read on to discover how useful these new features are in your daily development work.

Back to NS_OPTIONS

To understand OptionSetTypes, it helps to step back and look at Objective C's bit fields. In iOS 6 and OS X Mountain Lion, Apple introduced NS_OPTIONS along with its sibling NS_ENUM to replace typedef enum statements.

These macros created a consistent way to build bitflags and enumerations. They allow compilers to test for completeness in switch statements, ensuring that all cases are covered. They also specify both the type and size of option and enumeration members.

Many Objective-C constructs use NS_OPTIONS to create bit flag sets. For example, you might want to add an option about extending a view controller view's top and left edges. In Objective-C, you can or together UIRectEdgeTop and UIRectEdgeLeft values provided by the UIRectEdge option set. This option set also offers a UIRectEdgeAll option that combines all edges into a single value.

This convenience does not yet extend to OptionSetType instances. When you print option sets created in this article, they look something like C.UIRectEdge(rawValue: 14) or Features(rawValue: 194). That's both ugly and not particularly helpful.

I doubt this lack of print support will continue for long. The developer community should file sufficient bug reports with Apple to effect change.

Until then, you can create a custom representation using the CustomStringConvertible. This protocol replaces the Printable protocol in Swift 2.0. The following extension applies the new Swift 2.0 for-in-where construct to gather just those flags contained in the active set and returns a string representation of those members.

Wrap Up

This article highlights just one of the great new Swift 2.0 features available in Xcode 7. These updates simplify bitflags for existing Cocoa and Cocoa Touch NS_OPTIONs and for your own custom implementations. These changes make option sets more approachable and usable from your Swift code. I encourage you to explore this new feature. It's a simple and very welcome upgrade.