Friday, April 1, 2011

How to use enums in objective c?

We can use enums to define data types which will take only some specific values.
Often we come across code that has magic numbers in it.

See the code snippet below:
if (choice == 1)

What choice is intended by 1 is unclear over here.
So for this purpose we can use constants with meaningful names.

For instance, suppose the choice equals 1 means "edit Data"
so we can define a constant as follows:
const int kSelectedEditData = 1;

and we could rewrite the code above as follows:
if (choice == kSelectedEditData)

This makes it more readable. Suppose we want to do some processing in a switch statement, this approach would not work as the switch statement does not allow the use of constant values.
So inorder to get over this limitation we define an enum for all the choices and use that enum in the switch.

enum {
      kSelectedEditData = 1,
    } Choices;

You can now create a variable of this enum type as follows:
enum Choices myChoices;

Notice that we have to use the enum keyword during declaration which is not a very pretty sight. Just create a typedef to get rid of that.
typedef enum Choices Choices;

So now you can declare your enum variable as follows:
Choices myChoices;

Ok, now lets see how we can use this in a switch statement:
switch (myChoices){
   case kSelectedEditData:
      // do something

   case kSelectedDeleteData:
      // do something

   case kSelectedDisplayData:
        // do something

There, now everything is much more readable.

The only problem with the enum type is even if you declare a variable of the enum type, the compiler will not give you an error if you set a value other than the enum values to this type.
eg:- myChoices = 10; // no compiler errors

So enums are not type safe in objective c, but you can use them to make meaningful data types.


  1. Now I can understood why people use Enums

  2. I can understood too, yes. Very nice, I like