Switch-case alternative to test a subset of bits in an Option Set?

302 views Asked by At

I have an Option set that I use to efficiently store various information about an object. I.e. the first 6 or so bits determine the "type", and several bits determine whether or not it is in certain states, which may or may not be mutually exclusive.

I had this all as one big option set. I know one implementation option for me would be to go back and rework it into separate enumerations. Alas, that would be a lot more difficult, and I really liked the one int that needed to be stored to hold all of this information.

Currently, I'm unable to use a switch case, because the value rarely matches a single option. I want to be able to do a switch case on the type part, and a separate switch case on the state parts. But, the only implementation I could find was some ugly if / else chains.

Is there some other operation I may be missing that can accomplish this better?

1

There are 1 answers

0
Jake T. On

So, I had this brain blast while typing the question, but since I had first done some searching and didn't find anything helpful, I thought I'd post anyway.

This only works if you are trying to test a mutually exclusive subset of options. I.e. I mentioned the first few bits of mine determine a type or category. Within the definition of option sets, you have the flexibility to define some other values. Here I add an 'allTypes' option that encompasses all of the bits that determine types.

typedef NS_OPTIONS(NSInteger, kPropertyState) {
    kTypeNone                            = 0,
    kType1                               = 1,
    kType2                               = 1 << 1,
    kType3                               = 1 << 2,
    kState1                              = 1 << 3,
    kState2                              = 1 << 4,
// ... ... ...
    kAllTypes                            = kType1 | kType2 | kType3
};

Then, when I want to perform a switch case check on the type, I can do this:

kPropertyState propertyState = // ... However this was obtained

switch( propertyState & .kAllTypes ) {
    case kType1: // ...
    case kType2: // ...
    case kType3: // ...
    default: // . . .
}

Simply use a bit-wise and to isolate the bits. Since these bits are mutually exclusive from one another, you don't have to worry about other bits throwing off the case checks. Additionally, by putting the bitwise and inside the switch statement, my propertyState isn't actually changed and I still have access to other state bits for inside the relevant case blocks.