The use of bitwise operations to hold multiple options in one value is a common pattern and is used throughout the Cocoa Touch framework, with one example being UIDeviceOrientation. In Swift, there is a protocol, OptionSet, that formalizes this pattern and provides additional convenience. In this recipe, we will explore how to define your own option sets.
How to do it...
Let's rewrite our example from the last recipe, which defined supported device values, to use an OptionSet:
struct Devices: OptionSet {
let rawValue: Int
static let phone = Devices(rawValue: 1 << 0)
static let tablet = Devices(rawValue: 1 << 1)
static let watch = Devices(rawValue: 1 << 2)
static let laptop = Devices(rawValue: 1 << 3)
static let desktop = Devices(rawValue: 1 << 4)
static let tv = Devices(rawValue: 1 << 5)
static let brainImplant = Devices(rawValue: 1 <<...