有没有办法在目标C(在XCode中)使用带有范围的switch语句,假设是这样的:
- (NSString *)evaluate:(NSInteger)sampleSize
{
NSString returnStr;
switch (sampleSize)
{
case sampleSize < 10:
returnStr = @"too small!";
break;
case sampleSize >11 && sampleSize <50:
returnStr = @"appropriate";
break;
case sampleSize >50:
returnStr = @"too big!";
break;
}
return returnStr;
}
Run Code Online (Sandbox Code Playgroud)
Hug*_*ugh 41
有一个GCC扩展(我认为在Clang中支持)可能适合您.它允许您在case语句中使用范围.完整的文档位于http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges-该页面的示例案例陈述是
case 1 ... 5:
Run Code Online (Sandbox Code Playgroud)
这将匹配(不出所料)1,2,3,4或5.
不,switch 语句适用于大多数语言中的常量值...您能得到的最接近的是将案例彼此流动,如下所示:
switch(sampleSize)
{
case 0:
case 1:
case 2:
returnStr = @"too small!";
break;
}
Run Code Online (Sandbox Code Playgroud)
或者,这个问题可能会有所帮助......
编辑:我只是想到了另一种方法:您可以在 .h 文件中“#define”大量案例列表,如下所示:
#define TOO_LOW case 0: \
case 1: \
case 2: \
case 3:
Run Code Online (Sandbox Code Playgroud)
然后在 switch 中使用它,如下所示:
switch(sampleSize)
{
TOO_LOW
returnStr = @"too small!";
break;
}
Run Code Online (Sandbox Code Playgroud)
当然,这不是最干净的解决方案。3 个“if/else”有什么问题?