I like the smell of Swift in the morning…

How to remove an option from a NS_OPTIONS bitmask

Posted: | Author: | Filed under: Objective-C | No Comments »

I really like the NS_OPTIONS macro. I think it is a neat and tidy way to store multiple boolean values in one bitmask.

So for example if you have a car object that stores the features a customer ordered for his new car you could define something like:

typedef NS_OPTIONS(NSInteger, Feature) {
    FeatureNavigationSystem = (1 << 0),
    FeatureHeatedSteeringWheel = (1 << 1),
    FeatureParkDistanceControl = (1 << 2),
    FeatureSunRoof = (1 << 3),
    FeatureConvertible = (1 << 4)

Now you can store the features that a customer selected in one NSInteger (or in this case 'Feature') value using the bitwise OR operator (|):

Feature selectedFeatures = FeatureNavigationSystem | FeatureParkDistanceControl;

To check if a customer has selected a certain feature you use the bitwise AND operarator (&):

if (selectedFeatures &= FeatureNavgiationSystem) {
    // user has selected navigation system

Now there might be a situation where you want to remove a feature from the bitmask of selected options. In my simple example that might be the case when a user selects the option FeatureConvertible. If the customers does that, you might want to make sure that the feature FeatureSunRoof is not selected (because obviously a convertible does not have a roof).

So you want to remove the option FeatureSunRoof from the selected options while leaving the rest of the selected options as they were. This is where our friend the bitwise NOT operator (~) comes into play:

selectedOptions &= ~FeatureSunRoof

This removes the FeatureSunRoof from the selectedFeatures bitmask.

Leave a Reply