typedef NS_ENUM vs typedef enum

16,958

Solution 1

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).

Second, the compiler specifically recognises the NS_ENUM macro, so it knows that you have an enum with values that shouldn't be combined like flags, the debugger knows what's going on, and the enum can be translated to Swift automatically.

Solution 2

NS_ENUM allows you to define a type. This means that the compiler can check if you're assigning the enum to a different variable like so:

//OK in both cases
NSInteger integer = SizeWidth;
//OK only with typedef
BOOL value = SizeHeight;

NS_ENUM also provides checks in switch statements that you've covered all possible values:

//Will generate warning if using NS_ENUM
switch(sizeVariable) {
    case SizeWidth:
        //Do something
}
Share:
16,958

Related videos on Youtube

Alex Salom
Author by

Alex Salom

I'm Alex Salom, a Software Engineer. I talk Swift and Objective-C. iOS is my passion. I will understand you in English, Spanish and Catalan. Probably auch auf Deutsch.

Updated on June 04, 2022

Comments

  • Alex Salom
    Alex Salom almost 2 years

    On the Adopting Modern Objective-C guide, Apple recommends using the NS_ENUM macro instead of enum. I've also read an explanation from NSHipster about NS_ENUM and NS_OPTIONS.

    Maybe I've missed something but I don't quite understand what is the difference between the following two snippets and if any why is NS_ENUM the recommended way to go (except maybe, for backwards compatibility with older compilers)

    // typedef enum
    typedef enum {
        SizeWidth,
        SizeHeight
    }Size;
    
    // typedef NS_ENUM
    typedef NS_ENUM(NSInteger, Size) {
        SizeWidth,
        SizeHeight
    };
    
    • pronebird
      pronebird over 9 years
      Why don't you check the source code of that macro to get a clue, it's all in Xcode available for free and takes one click.