switch case on NSString in objective c [duplicate]

扶醉桌前 提交于 2019-12-03 05:21:31

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/19067785/switch-case-on-nsstring-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!