Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Don't get what happened when we declared the enum......

What is going on when we declare:

typedef enum menuChoice {..........} menuChoice?

I think it was an important topic, but in the video it was never explained why we did this and what's going on behind the scenes...... Thanks for the help!!!

1 Answer

When you declare an enum like that, you're basically creating a type (so you can make functions and methods take only that type, for example), and then you're defining a list of possible values of that type. Say you have a class to represent a car, and you only want a car to be a specific set of colors. You could define an enum like this:

typedef NS_ENUM(NSInteger, MHCarColor){
    MHCarColorBlack,
    MHCarColorWhite,
    MHCarColorSilver,
    MHCarColorBlue,
    MHCarColorRed
};

and then define your Car class's initializer to take MHCarColor. That way you could do something like this:

[[MHCar alloc] initWithColor:MHCarColorBlack]; //or MHCarColorWhite, MHCarColorSilver, MHCarColorBlue, or MHCarColorRed

That initializer will only be able to take those specific values, so enums are a great way to define options for a type where there is a finite number of possible values

Also, that above example uses NS_ENUM, which is the newer, recommended method of defining enums, which you can read about on the NSHipster blog (which is a generally amazing place to learn about cool things in iOS programming)


If you wanna know what's going on under the hood, you're basically defining a bunch of integer constants that are generally entirely ceremonial, but can be whatever you want. Doing this:

typedef NS_ENUM(NSInteger, MHCarColor){
    MHCarColorBlack,
    MHCarColorWhite,
    MHCarColorSilver,
    MHCarColorBlue,
    MHCarColorRed = 100
};

is almost entirely equivalent to doing this:

typedef NSInteger MHCarColor;
static const MHCarColor MHCarColorBlack = 0;
static const MHCarColor MHCarColorWhite = 1;
static const MHCarColor MHCarColorSilver = 2;
static const MHCarColor MHCarColorBlue = 3;
static const MHCarColor MHCarColorRed = 100;

The enum method is generally accepted to be better, however, because it constrains the type (in this case, MHCarColor) to only have a certain number of possible values, it's a lot less typing, and it also works a lot better with Swift

Thanks a lot Michael for a super detailed answer!!! It helped a lot!!