Rostyslav Druzhchenko
Rostyslav Druzhchenko

Reputation: 3773

NS_ENUM vs enum

Objective C provides several ways to declare an enumeration. It could be declared via typedef enum or NS_ENUM. NS_ENUM macro takes type name as a parameter, and I do not completely understand its meaning. I didn't find description of NS_ENUM macro in official Apple documentation. What's a difference between using enum and NS_ENUM? And an other question if it's possible to use any other type in NS_ENUM instead NSInteger and its relative integer types?

Upvotes: 10

Views: 8836

Answers (3)

AydinAngouti
AydinAngouti

Reputation: 379

Here is the link to the official Apple's documentation:
https://developer.apple.com/library/content/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html#//apple_ref/doc/uid/TP40014150-CH1-SW6

From the subsection titled "Enumeration Macros":

The NS_ENUM and NS_OPTIONS macros provide a concise, simple way of defining enumerations and options in C-based languages. These macros improve code completion in Xcode and explicitly specify the type and size of your enumerations and options. Additionally, this syntax declares enums in a way that is evaluated correctly by older compilers, and by newer ones that can interpret the underlying type information.

Use the NS_ENUM macro to define enumerations, a set of values that are mutually exclusive:

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
        UITableViewCellStyleDefault,
        UITableViewCellStyleValue1,
        UITableViewCellStyleValue2,
        UITableViewCellStyleSubtitle
};

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.

Upvotes: 2

Sergiu Todirascu
Sergiu Todirascu

Reputation: 1437

The main difference is that typedef NS_ENUM translates to a Swift enum properly, whereas typedef enum doesn't.

Upvotes: 10

Stavash
Stavash

Reputation: 14304

NSHipster provided a very nice post that explains this thoroughly:

http://nshipster.com/ns_enum-ns_options/

To quote the bottom line:

This approach combines the best of all of the aforementioned approaches (enum, typedef enum), and even provides hints to the compiler for type-checking and switch statement completeness.

Upvotes: 13

Related Questions