Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The new enum in Objective-C

In the latest tools, a new kind of enums are now allowed:

typedef enum CarType : NSUInteger {   FourDoorCarType,   TwoDoorCarType } CarType; 

My question comes in parts:

  1. Why should I use this instead of the old way?

  2. Why does CarType appear twice? I tried skipping the first CarType and just leaving the first line as "typedef enum : NSUInteger {", and it seems to work fine. What are the drawbacks, if any?

  3. Can some types other than NSUInteger be used?

like image 404
NoobOverflow Avatar asked Jul 20 '12 08:07

NoobOverflow


People also ask

How to create enum in Objective-C?

Objective-C Language Enums Defining an enumtypedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, }; You can also specify on the first value and all the following will use it with increment: typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB, MyEnumValueC, };

What is enum base type in Objective-C?

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.

Can we use swift enum in Objective-C?

Event though Swift supports string enums they cannot be used in Objective-C, only Int enums are allowed.

What is typedef Objective-C?

The typedef function is used to assign the new name to the datatype. So that you can use a custom name for predefined long names of the datatypes.


1 Answers

Because this new way helps you with autocompletion, switch statement, better, respectively more precise warnings, ...

Stick with macro ...

typedef NS_ENUM( NSUInteger, CarType ) {   FourDoorCarType,   TwoDoorCarType }; 

... read this for example https://stackoverflow.com/a/3190470/581190

NSInteger, ... what types do you want?

like image 102
zrzka Avatar answered Oct 01 '22 21:10

zrzka