blog

Home / DeveloperSection / Blogs / Objective C Data Type - Enum

Objective C Data Type - Enum

Tarun Kumar 2254 04-Jul-2015

Objective-C have a data type that allows you to create a type that will only take certain, predefined values. This is particularly useful, as it allows the programmer to model real-world collections, such as the months of the year, or the players in a game with a specific number of players. The syntax is quite simple. To create a Direction type as might be found in a map application, use the following code: 

enum direction {north, south, west, east};

You can then use it anywhere else you might have a variable:

enum direction currentDirection = south;


         // …
         if (currentDirection == north)
              NSLog(@"Player is going north.");
         // …

- Note that an enumerated type is simply a specific list of integers, where each value is given one (or more) names. By default, the first element in a list is set equal to 0, and each subsequent element is assigned a value one greater. In the example above, the value north is equivalent (in all contexts) to the integral constant 0, south is equal to 1, and so on. You can also specify an integer value to be equal to an enumerated value:

enum direction {north, south = 5, west = 4, east}; 

Here, north is equal to 0, south is equal to 5, west is equal to 4, and because no value has been specified for east, it uses the “next” value after the previous declaration—therefore, east is equivalent to 5. This is perfectly acceptable—in one enum, multiple values can share one representative value.

The syntax for declaring an enumeration is as follows:

enum <name> { <value name 1>, <value name 2>, ... };

In the above syntax outline, enum is the keyword that tells the compiler we are creating an enumeration, <name> is the name to be assigned to the enumeration and the <value name> fields are the names that can be used to set the variable. Internally, enumerators use numbers corresponding to the value names. By default the first value corresponds to 0, the second to 1 and so on. It is also possible to specify the values used by each value name:

enum <name> { <value name 1> = <value1>, <value name 2> = <value2>, ... };

For example, we can specify an enumeration for the days of the week:

enum daysofweek {monday, tuesday, wednesday, thursday, friday, saturday, sunday};

In the above construct, Monday is equal to 0, Tuesday is 1 and so on. If we specify a number for just one entry, the remaining values will follow on from that number. For example:

enum daysofweek {monday = 1, tuesday, wednesday, thursday, friday, saturday, sunday};

In this case, Monday will be 1, Tuesday will be 2 etc.

Next, we will learn about: Objective C - Understanding “extern” keyword


Updated 24-Feb-2018

Leave Comment

Comments

Liked By