Alex Gray
Alex Gray

Reputation: 16473

How do I create "or'ed" switches using typedef enum?

I kinda like enums. Their syntax is arcane-looking, and I've yet to find a definitive point of reference on their undeniably proper use.. but let's say I had..

typedef enum {
    OrientTop,
    OrientBottom,
    OrientFiesta
}   Orient;

I'd love to be able, as I do with, for example, other constants when multiple chocies may be applicable/ required, just do…

 self.orientation = OrientTop | OrientFiesta;  // NO NO WORK-O!

just like one does with…

self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;

or also..

it = [[NSThing alloc]initOptions: NSStupid | NSSpicy | NSSassy];

and it would also be nice.. instead of…

 if ((o == OrientTop ) || ( o == OrientBottom))

i could just use…

if (o == OrientTop || OrientBottom) 

and most importantly… how to check multiple cases, á la..

switch (orientation) {
    case OrientTop | OrientBottom:

Or something, of the sort.. ugh, oh.. you guys are too slow.. so, duh.. i just need to…

case OrientLeft:
case OrientRight:  { // blah blah blah
     break;        }

(But for the first part.. ) What is the extra "secret sauce" that Apple / smarter people than me.. are using to give their typedef's that extra zing that make mine taste so, ech..bland.. in comparison?

Upvotes: 1

Views: 392

Answers (1)

ravron
ravron

Reputation: 11221

It appears as if typedefs such as NSViewWidthSizable are actually bitmasks, which allow the nice ORing operations you so enjoy. In the headers for some UIKit elements, you can see what I mean:

enum {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;

I snatched that right off a very helpful site that explains in more detail, but you can also examine the enumeration of any constant by holding Command ⌘ and clicking the constant or typedef.

Upvotes: 3

Related Questions