I have always wondered but can’t find a definitive answer. When should I use either an ‘if’ or ‘switch’ statement. When is one better than the other?
For example I could do:
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
//Stuff
break;
case 1:
//Stuff
break;
default:
break;
}
//OR
if (buttonIndex == 0) {
//Stuff
}
if (buttonIndex == 1) {
//Stuff
}
}
This is just an example, but I’m sure in different situations to this it would matter differently.
I believe this is a subjective question. The answer is really up to you.
For my own code, I like using
switchstatements as it’s pretty clear that what is happening is the result of some condition that can do other things if the condition is different.But if the code underneath a
switchcase:statement is rather lengthly or convoluted, then for my own code I do the second thing: theif (buttonIndex == 0) {bit.