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)

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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"); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.