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.
In this case this doesn't matter. The reason switch exists is that it's faster than if. If you write a long code of if ... else if ... else if ...
it will perform slower than switch because if
does iterative search (O(n)) while switch
does table based lookup (O(1))
I believe this is a subjective question. The answer is really up to you.
For my own code, I like using switch
statements 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 switch
case:
statement is rather lengthly or convoluted, then for my own code I do the second thing: the if (buttonIndex == 0) {
bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With