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;
}
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.
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...");
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With