0

How to create switch statement with accept string parameter

-(int)Type:(NSString *)typeName{

    switch (typeName) {
        case @"MEN":
            NSLog(@"MEN");
            break;
        case @"FEMALE":
            NSLog(@"FEMALE");
            break;
        default:
            NSLog(@"FEMALE");
            break;
    }

}

I test it in php which is working fine

$name = "JHON";

switch ($name) {

case "JHON" :
{
echo "Im JHON";
break;
}

case "KIRAN":
{
echo "Im KIRAN";
break;
}

default:{
echo "Im default";
}

}
?>

Switch case which accept string condition is not working objective-c its error message says statement requires expression of integer type. (NSString _string invalid)

kiran
  • 4,285
  • 7
  • 53
  • 98

3 Answers3

1

Well, the error you get kinda gives it away, switch in objective-c only works with integers, not strings...

Fabio Ritrovato
  • 2,546
  • 1
  • 13
  • 19
0

As mentioned, you cannot usually use switch with things that are not integers (in the most popular programming languages, Objective-C included). However, you can check this question for a way to get close to the syntax without having to resort to if-else.

Community
  • 1
  • 1
alxgb
  • 543
  • 8
  • 18
0

In Objective C you cannot use Strings in Switch, but you can do alternatively using NSDictionary, check this stackoverflow link for reference. So from the link, your code can be rewritten like

typedef void (^CaseBlock)();

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                   ^() { NSLog(@"MEN"); }, @"MEN",
                   ^() { NSLog(@"WOMEN"); }, @"WOMEN",
                   ^() { NSLog(@"MALE"); }, @"MALE",
                   ^() { NSLog(@"FEMALE"); }, @"FEMALE",
                   nil];

CaseBlock c = dict[@"MEN"];
if (c) c(); else { 
   // default: case
   NSLog(@"Female"); 
}
Community
  • 1
  • 1
arthankamal
  • 6,341
  • 4
  • 36
  • 51