在目标 c 中切换 NSString 的大小写 [英] switch case on NSString in objective c
问题描述
我想在 NSString 中使用 case 语句请将我的代码更改为正确的代码
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");
})();
我更喜欢前者.
这篇关于在目标 c 中切换 NSString 的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!