13

Is this the correct (or even a valid way) to use emums in Objective-C? i.e. The menuItem is not used but just defines a list add=1, load=2, list=3 etc.

enum menuItems {
    add = 1    ,
    save       ,
    load       ,
    list       ,
    removeAll  ,
    remove     ,
    quit       
};

int optionSelect;

scanf("%d", &optionSelect);

switch (optionSelect) {
    case add: 
        //...
        break;
}

cheers gary

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • 2
    Added the C tag since you're not doing any Obj-C here. Just to point out that valid C is totally valid within Obj-C. :) – Pascal Nov 02 '09 at 17:27

3 Answers3

17

If you want to give a semantic meaning to the enumeration, you can consider to define a customized type and declare the variable "optionSelect" as variable of that type! In code...

typedef enum menuItems {
       add = 1,
       save,
       load,
       list,
       removeAll,
       remove,
       quit} MenuItem;


MenuItem optionSelect;

scanf("%d", &optionSelect);

switch (optionSelect) {
    case add: 
    ...
    break;
    .
    .
    .
}

That is, almost, the same thing you have written, but from the side of the developer you give a particular meaning to the variable "optionSelect", not just a simple int!

BitDrink
  • 1,185
  • 1
  • 18
  • 24
  • 1
    Be sure to check out `NS_ENUM` and `NS_OPTIONS`. These Apple provided macros take much the guesswork out of writing enums. http://nshipster.com/ns_enum-ns_options/ – BergQuester Oct 05 '13 at 02:16
4

In this, the future, it's possibly also helpful to mention NS_ENUM. You'd use it like:

typedef NS_ENUM(uint16_t, TYEnummedType)
{
    TYEnummedType1,
    TYEnummedType2
};

That has almost the same effect as a normal enum and typedef but explicitly dictates the integer type, which is really helpful if you ever want to pack these things off somewhere, be precise in your struct alignment, amongst other uses.

It was added to the iOS SDK with version 6 and OS X with 10.8 but it's just a C macro and doesn't add anything that you couldn't do with vanilla typedef and enum, so there's no backwards compatibility to worry about. It exists only explicitly to tie the two things together.

Tommy
  • 99,986
  • 12
  • 185
  • 204
1

Your way will work. However, if you would like to use menuItems as a type for variables or parameters, you will need to do a typedef:

typedef enum {add = 1,save,load,list,removeAll,remove,quit}  menuItems;
menuItems m = add;
[myobj passItem:m];