In sample code, I have seen this:
typedef enum Ename { Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John};
but what compiled successfully for me was this:
enum {Bob, Mary, John};
I put that line in a .h file above the @interface line, and then when I #import that .h file into a different class's .m file, methods there can see the enum.
So, when are the other variants needed?
If I could name the enum something like EmployeeNames, and then, when I type "EmployeeNames" followed by a ".", it would be nice if a list pops up showing what the enum choices are.
A typedef in Objective-C is exactly the same as a typedef in C. And an enum in Objective-C is exactly the same as an enum in C. This declares an enum with three constants kCircle = 0, kRectangle = 1 and kOblateSpheroid = 2, and gives the enum type the name ShapeType.
First, NS_ENUM uses a new feature of the C language where you can specify the underlying type for an enum. In this case, the underlying type for the enum is NSInteger (in plain C it would be whatever the compiler decides, char, short, or even a 24 bit integer if the compiler feels like it).
An introduction to C Enumerated TypesUsing the typedef and enum keywords we can define a type that can have either one value or another. It's one of the most important uses of the typedef keyword. This is the syntax of an enumerated type: typedef enum { //...
Enums are defined by the following the syntax above. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA, MyEnumValueB, MyEnumValueC, }; You also can set your own raw-values to the enumeration types. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, };
In C (and hence Objective C), an enum type has to be prefixed with enum
every time you use it.
enum MyEnum enumVar;
By making a typedef:
typedef MyEnum MyEnumT;
You can write the shorter:
MyEnumT enumVar;
The alternative declarations declare the enum itself and the typedef in one declaration.
// gives the enum itself a name, as well as the typedef
typedef enum Ename { Bob, Mary, John} EmployeeName;
// leaves the enum anonymous, only gives a name to the typedef
typedef enum {Bob, Mary, John} EmployeeName;
// leaves both anonymous, so Bob, Mary and John are just names for values of an anonymous type
typedef enum {Bob, Mary, John};
The names inside enum { }
define the enumerated values. When you give it a name, you can use it as a type together with the keyword enum
, e.g. enum EmployeeName b = Bob;
. If you also typedef
it, then you can drop the enum
when you declare variables of that type, e.g. EmployeeName b = Bob;
instead of the previous example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With