I don't think I fundamentally understand what an enum is, and when to use it.
typedef enum {
kPersonTypeFaculty,
kPersonTypeStaff,
kPersonTypeSearch
}
so please give idea about why using enum and how to used enum
I don't think I fundamentally understand what an enum is, and when to use it.
typedef enum {
kPersonTypeFaculty,
kPersonTypeStaff,
kPersonTypeSearch
}
so please give idea about why using enum and how to used enum
Enums aren't entirely necessary but they make code easier to read and understand. Take this piece of code for instance:
switch(type){
case 0:
//do something
break;
case 1:
//do something else
break;
case 2:
//do something else
break;
default:
//do the general case
break;
}
Just from that piece of code it is impossible to figure out what each case statement is responsible for handling.
If we use the enum, this is what it would look like, the compiler will also help us if we happen to leave out the default statement and miss a case:
switch(type){
case kPersonTypeFaculty:
break;
case kPersonTypeStaff:
break;
case kPersonTypeSearch:
break;
default:
break;
}
If you declare your enum more rigidly:
typedef enum CardState : NSUInteger {
CardStateActivated = 0,
CardStateArchived = 1,
CardStateDepleted = 2,
CardStateUnauthorized = 3
} CardState;
What you can do now is use the enum type as an argument to methods. Such as:
- (void) reloadCardWithState:(CardState) state;
This could obviously be done with NSInteger
or int
but it just makes the code more readable and helps a lot when figuring out errors. It also makes coding in an editor like XCode easier, as you will know the method requires a CardState and you can then go and look which state you would like to use or are using.