Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use an if or switch Statement? Objective-C

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.

like image 435
Josh Kahane Avatar asked Dec 03 '11 14:12

Josh Kahane


2 Answers

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))

like image 89
Dani Avatar answered Oct 13 '22 12:10

Dani


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.

like image 35
Michael Dautermann Avatar answered Oct 13 '22 11:10

Michael Dautermann