Thursday, 10 April 2014

iPhone Development: Why to use Enumeration(enum)





Enumeration, normally called as enum. Listening to this term raise one question in mind that why we use it and how can we use it. The idea behind using enum is to use a type value rather then using int value.Below is the example that will provide you a better understanding of enum

 if we have 3 different color of ball then to select one ball we will pass int to it in our switch statement

switch(typeofBall)
{
        case 0:
            //do something
            break;
        case 1:
            //do something else
            break;
        case 2:
            //do something else
            break;
        default:
            //do the general case
            break;
}
 
 Now in above code it is hard for some one to check what each case do as they are mere
  numbers and to check what each condition/case perform we have to look for the statements
 written before break statement.

If we perform the same task using enum then it will be 
 

switch(type){
        case ballColorRed:
            break;
        case ballColorYellow:
            break;
        case ballColorBlue:
            break;
        default:
            break;
    }
 
Now look it carefully that in above code 
it is clearly stated that what task is performed by each case.We can declare it as  

 
typedef enum BallSelection : NSUInteger {
    ballColorRed = 0,
    ballColorYellow = 1,
    ballColorBlue = 2,
    ballColorNotSelected = 3
} BallSelection;  
 
enum in objective c as To use it in a method, you can use below code

- (void)reloadCardWithState:(BallSelection) selection;  

No comments:
Write comments