12

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;
}
nmokkary
  • 1,219
  • 3
  • 14
  • 24

2 Answers2

55

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.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • +1 nice. I am all for separating data and code. –  Sep 28 '13 at 14:20
  • it's amazing. can you please explain this code – nmokkary Sep 28 '13 at 14:57
  • That is a pretty cool piece of code. You have almost created another control structure. – JeremyP Nov 27 '13 at 17:21
  • 1
    @nmokkary The code creates an NSDictionary literal of code blocks keyed on the string cases. It then returns the code block keyed on the `key` variable. Then, if the returned code block is non nil, it executes it. – JeremyP Nov 27 '13 at 17:24
  • 3
    Clever, but extremely difficult to read. Curse you, block syntax! I'd just stick to if/else. – GoldenJoe May 20 '15 at 04:34
3

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...");
       }
...
GeneralMike
  • 2,951
  • 3
  • 28
  • 56
Antonio MG
  • 20,382
  • 3
  • 43
  • 62