A type that presents a mathematical set interface to a bit mask.
- Xcode 8.0+
You use the
Option protocol to represent bit mask types, where individual bits represent members of the set. Adopting this protocol in your custom types lets you perform set-related operations such as membership tests, unions, and intersections on those types. What’s more, when implemented using specific criteria, adoption of this protocol requires no extra work on your part.
When creating an option set, include a
raw property in your type declaration. The
raw property must be of a type that conforms to the
Bitwise protocol, such as
UInt8. Next, create unique options as static properties of your custom type using unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual property’s raw value so that each property can be represented by a single bit of the type’s raw value.
For example, consider a custom type called
Shipping that is an option set of the possible ways to ship a customer’s purchase.
Shipping includes a
raw property of type
Int that stores the bit mask of available shipping options. The static members
Standard are unique, individual options.
Declare additional preconfigured option set values as static properties initialized with an array literal containing other option values. In the example, because the
express static property is assigned an array literal with the
second options, it will contain those two elements.
Using an Option Set Type
When you need to create an instance of an option set, assign one of the type’s static members to your variable or constant. Alternatively, to create an option set instance with multiple members, assign an array literal with multiple static members of the option set. To create an empty instance, assign an empty array literal to your variable.
Use set-related operations to check for membership and to add or remove members from an instance of your custom option set type. The following example shows how you can determine free shipping options based on a customer’s purchase price: