对于大型switch语句,是否有更优雅的解决方案?

Pfi*_*itz 1 optimization objective-c switch-statement ios

我已经将很多范围映射到0-300 = 10,300-600 = 20,600-900 = 30 ... 2500000-2700000 = 7000 ......所以我可以制作一个非常大的开关 - 声明/ if-block但我想知道是否有更优雅的方法来解决这个小问题.

好的,这是表的一小部分,包含真实数据:

0-300 : 25
301-600.  : 45
601-900 : 65
901-1200. : 85
1201-1500: 105

1501-2000 : 133
2001-2500 : 161
2501-3000: 189
3001-3500:217
3501-4000:245

4001-4500:273
4501-5000:301
5001-6000:338
Run Code Online (Sandbox Code Playgroud)

yuj*_*uji 5

摆脱switch语句最常见的模式是使用字典.在您的情况下,由于您是映射范围,因此您将使用NSArray范围截止值.如果你正在处理int,那就是它的样子:

NSArray *rangeCutoffs = [NSArray arrayWithObjects:[NSNumber numberWithInt:300],[NSNumberWithInt:600],...,nil];
NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:20],...,nil];

int mappedInt;
for (int index=0; index <= [rangeCutoffs count]; index++) {
    if (intToMap < [[rangeCutoffs objectAtIndex:index] intValue]) {
        mappedInt = [[values objectAtIndex:index] intValue];
    }
}
if (mappedInt == 0) {
    mappedInt = [[values lastObject] intValue];
}
Run Code Online (Sandbox Code Playgroud)

在实践中,你想要从plist 加载rangeCutoffsvalues不是硬编码.