Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone switch statement using enum

I have defined an enum in a header file of a class :

typedef enum{
 RED = 0,
 BLUE,
 Green
} Colors;

- (void) switchTest:(Colors)testColor;

and in the implementation file I have :

- (void) switchTest:(Colors)testColor{

   if(testColor == RED){
    NSLog(@"Red selected");    
   }

   switch(testColor){
    case RED:
    NSLog(@"Red selected again !");
    break;
    default:
    NSLog(@"default selected");
    break;
   }

}

My code compiles correctly without warrnings. When calling the switchTest method with RED, the output is : "Red selected"

but once the first line of the switch runs, the application quits unexpectedly and without warrnings/errors.

I don't mind using if/else syntax but I would like to understand my mistake.

like image 897
shortstacker Avatar asked Jun 02 '10 18:06

shortstacker


People also ask

How do you use enum switch case?

An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default. enum constants are accessed using dot syntax. An enum class can have attributes and methods, in addition to constants.

What is difference between enum and switch?

First, the switch case uses the name you declared for your variable. The enum holds the logic, and your variable allows you to access the logic. Using the same name in your switch case allows you to access the variable. Think of it like a locked room.

Can enum be used in switch case in C?

Example of Using Enum in Switch Case Statement We will then use the switch case statements to switch between the direction elements and print the output based on the value of the variable for the enum directions.


2 Answers

Works fine for me:

typedef enum{
    RED = 0,
    BLUE,
    Green
} Colors;

@interface Test : NSObject

- (void) switchTest:(Colors)testColor;
@end

@implementation Test

- (void) switchTest:(Colors)testColor {
    if(testColor == RED) {
    NSLog(@"Red selected");    
    }

    switch(testColor){
    case RED:
        NSLog(@"Red selected again !");
        break;
    default:
        NSLog(@"default selected");
        break;
    }
}
@end


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Test *myTest = [[Test alloc] init];

    [myTest switchTest:RED];

    [myTest switchTest:RED];

    [pool drain];
return 0;
}

like image 146
Badmanchild Avatar answered Oct 10 '22 10:10

Badmanchild


In my case, the problem was that I defined the variable:

Colors *testColor; //bad

Instead of:

Colors testColor; //right

Hope it helps.

like image 20
Villapalos Avatar answered Oct 10 '22 10:10

Villapalos