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?
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).
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, };
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.
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