How to Accept Multiple Enum Values in a Property or Method | Techbirds

First, let’s go over what an enum is and how to create one. An enum, short for enumeration, is a user-defined type consisting of a set of named constants called enumerators. It is used to group related values in a strongly-typed way. Behind the scenes, each enumerator maps to an integer. If we don’t specify explicit integer values, the compiler will automatically assign values sequentially starting from 0. In this example, we’ll be setting explicit integer values that are increasing powers of 2. We’ll also be using the new NS_ENUM syntax introduced in iOS 6:
typedef NS_ENUM(NSInteger, MRColor) {

MRColorNone = 0,

MRColorRed = 1,

MRColorBlue = 2,

MRColorWhite = 4,

MRColorGreen = 8

}; Now let’s imagine invoking a method with several of these color values at once, like this: [self paint:MRColorRed|MRColorBlue]; In C, we combine multiple enum values by separating them with a vertical pipe. This symbol represents a bitwise OR operation. It returns 1 if either binary value is 1, and returns 0 if not. Here’s what happens if perform an OR operation on the numbers 1 and 2:

1: 0001

2: 0010

—-

0011 which is 3

So our method receives a color value of 3 as its input. Now, we can use something called the bitwise AND operator (&). It returns 1 if both binary values are 1, and returns 0 if not. Here’s what happens if perform an AND operation on the numbers 3 and 1:

3: 0011

1: 0001

—-

0001 which is 1 We get 1, which is the value of MRColorRed! So that means that inside our method, we simply need to perform a binary AND on the input parameter and every possible enum value to see if it was included, like this:

– (void) paint:(MRCarColor)color

{

if (color | MRColorRed == MRColorRed)

//red was included

}

if (color | MRColorBlue == MRColorBlue)

//blue was included

}

}
This only works because we chose powers of 2 as our enum values. This allows each enum value to map to a single bit in our input integer value.

378 total views, 2 views today

Share this Onfacebook-5362942twitter-6256007linkedin-7607081google-8145357