Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef NS_ENUM vs typedef enum

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
};
like image 275
Alex Salom Avatar asked Nov 28 '14 15:11

Alex Salom


People also ask

What is Ns_enum?

The NS_ENUM macro helps define both the name and type of the enumeration, in this case named UITableViewCellStyle of type NSInteger . The type for enumerations should be NSInteger .

What is typedef enum 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.


1 Answers

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.

like image 80
gnasher729 Avatar answered Sep 19 '22 17:09

gnasher729