Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case on NSString in objective c [duplicate]

i want to use case statement with NSString please change my code to correct code

NSString *day = @"Wed";

switch (day) {
    case @"Sat":
        NSlog(@"Somthing...");
        break;

    case @"Sun":
        NSlog(@"Somthing else...");
        break;  
        .
        .
        .
        .

    default:
        break;
}
like image 905
nmokkary Avatar asked Sep 28 '13 14:09

nmokkary


2 Answers

If you want some slightly smarter dispatch than a long list of conditionals you can use a dictionary of blocks:

NSString *key = @"foo";

void (^selectedCase)() = @{
    @"foo" : ^{
        NSLog(@"foo");
    },
    @"bar" : ^{
        NSLog(@"bar");
    },
    @"baz" : ^{
        NSLog(@"baz");
    },
}[key];

if (selectedCase != nil)
    selectedCase();

If you have a really long list of cases and you do this often, there might be a tiny performance advantage in this. You should cache the dictionary, then (and don't forget to copy the blocks).

Sacrificing legibility for convenience and brevity here's a version that fits everything into a single statement and adds a default case:

((void (^)())@{
    @"foo" : ^{
        NSLog(@"foo");
    },
    @"bar" : ^{
        NSLog(@"bar");
    },
    @"baz" : ^{
        NSLog(@"baz");
    },
}[key] ?: ^{
    NSLog(@"default");
})();

I prefer the former.

like image 71
Nikolai Ruhe Avatar answered Oct 20 '22 13:10

Nikolai Ruhe


Switch statements don´t work with NSString, only with integers. Use if else:

NSString *day = @"Wed";

if([day isEqualToString:@"Sat"]) {
        NSlog(@"Somthing...");
       }
else if([day isEqualToString:@"Sun"]) {
        NSlog(@"Somthing...");
       }
...
like image 39
Antonio MG Avatar answered Oct 20 '22 15:10

Antonio MG