I'm working on several iOS projects where I think enumerated datatypes would be helpful to me. For example, I have a game where the player can walk in several directions. I could just define four constants with string values as kDirectionUp
, kDirectionDown
, etc.
I think an enumerated type would be better here. Is that correct? If so, how do I define an enum here so that I can later compare values? (As in, if(someValue == kDirectionUp){}
)
Enums are defined by the following the syntax above. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA, MyEnumValueB, MyEnumValueC, }; You also can set your own raw-values to the enumeration types. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, };
In this situation, one can declare the enumerated type in which only male and female values are assigned. It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or, Beside this, we can create enumerated type variables as same as the normal variables.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
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.
That sounds like the right thing to do.
It's really simple to create enums in Objective-C using C-style type definitions. For example, in one of my header files, I have the following type definition:
typedef enum {
CFPosterViewTypePoster = 0,
CFPosterViewTypeStart, // 1
CFPosterViewTypeEnd, // 2
.... // 3
} CFPosterViewType;
You define an object of CFPosterViewType and set it to one of the values:
CFPosterViewType posterType = CFPosterViewTypeStart;
When comparing CFPosterViewType values, it's as simple as doing the following:
if (posterType == CFPosterViewTypePoster) {
// do something
}
Note that the commented out numbers in the enum above are implicit values. If you want to do something differently, say, define a bitmask, or anything else where you need the values to be different than the default, you'll need to explicitly define them.
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