objective-c 在目标 c 中切换 NSString 的大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19067785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:02:17  来源:igfitidea点击:

switch case on NSString in objective c

objective-cnsstringswitch-statement

提问by nmokkary

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

我想在 NSString 中使用 case 语句,请将我的代码更改为正确的代码

NSString *day = @"Wed";

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

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

    default:
        break;
}

回答by Nikolai Ruhe

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.

我更喜欢前者。

回答by Antonio MG

Switchstatements don′t work with NSString, only with integers. Use if else:

Switch语句不适用于 NSString,只能用于整数。使用if else

NSString *day = @"Wed";

if([day isEqualToString:@"Sat"]) {
        NSlog(@"Somthing...");
       }
else if([day isEqualToString:@"Sun"]) {
        NSlog(@"Somthing...");
       }
...