Mike Richards
Mike Richards

Reputation: 999

Switch statement VS If statement

I have a lot of if statements, nested if statements, and if-else statements in my project and I'm thinking about changing them to switch statements. Some of these will have nested switch statements. I know that in terms of compiling, switch statements are generally faster. My question is, which is generally more preferred to use?

Upvotes: 2

Views: 4099

Answers (2)

jerrylroberts
jerrylroberts

Reputation: 3454

Here's an important distinction

A switch statement takes an expression with an integer result and matches it up to a case statement with a constant value. Case statements can not be expressions... so when you need to evaluate an integer result off a set of determined values then a switch statement makes sense.

IMO, nested switch statements will probably add confusion to your code... it's not just as readable.

Here's an example of where I used a switch statement to return the appropriate data source for a UIPickerView Component

- (NSMutableArray *) datasourceForComponent:(NSInteger)component
{
    switch (component) {

        case HoursPickerComponent: 
            return _hours;
            break;

        case MinutesPickerComponent:            
            return _mins;
            break;

        case DaysPickerComponent:            
            return _days;
            break;

        default:
            return nil;
            break;

   }    
}

This is a commonn patter I use to avoid magic strings or funky conditional logic. Since enums return an int result, I often use them for routing and decision points. Here I created an enum for my different datasources:

typedef enum
{
    HoursPickerComponent = 0,

    MinutesPickerComponent = 1,

    DaysPickerComponent = 2

} MedicationPickerComponents;

Then my delegate code for the UIPickerView component looks like

- (NSInteger)pickerView:(UIPickerView *)pickerView 
numberOfRowsInComponent:(NSInteger)component
{
    return [[self datasourceForComponent:component] count];
}

I feel this is a good example of how to use a switch for decision points to make code more readable. Notice that I didn't put a lot of logic in the case statement... this way you can easily tell the intention of this switch statement by looking at it. If I had more complex code to run, I would just stub that out in a method and call the method from my case statement.

Upvotes: 7

CraigAlbright
CraigAlbright

Reputation: 71

If the control flow is depending on the value of a variable having more than 1 or 2 values, a switch makes more sense and would be easier to read and maintain. I do not have a source to quote here, but I believe they would compile down to the same native code anyway, so its not a question of performance or efficiency. I think that you should code for readability, and as you have more conditions, a switch is preferable to multiple ifs.

Upvotes: 4

Related Questions