首先,我很抱歉问题标题。
现在,问题是: 我正在编写一个iPhone应用程序,它可以读取罗盘值并显示设备所面向的方向名称。写作时,我这样做:
switch (trueHeadingRounded) {
case 23 ... 68:
cardinalDirection = @"northeast";
break;
case 69 ... 114:
cardinalDirection = @"east";
break;
//ad infinitum
如何缩短这部分?必须有更好的方法。
答案 0 :(得分:5)
您可以执行以下操作:
(x - 23) / 45
或类似的东西。[0] => 'Northeast', [1] => 'East', etc.
return mappingArray[indexFromAngle(x)]
答案 1 :(得分:3)
不要编写代码来缩短它,编写代码以使其更容易理解。清晰就是一切。
如果为了清晰起见而对性能写入存在担忧,那么如果存在性能问题配置文件以确切找到什么和在哪里然后修复它。
答案 2 :(得分:1)
NSString* cardinalDirection = @[@"north", @"northeast", @"east", @"southeast", @"south", @"southwest", @"west", @"northwest", @"north"][(trueHeadingRounded + 23) / 45];
这可能是我关于23常数或其他一些 - 我没有仔细检查我的计算结果。 (但我有点同意扎普。)
(当然,如果你真的这样做,那么为了效率而将数组设为一个相对常量 - 类的属性或类似的属性可能是明智的。)
答案 3 :(得分:1)
您可以使用命名常量而不是幻数
来提高可读性typedef NS_ENUM(NSInteger, Heading) {
HeadingNorth = -1,
HeadingNorthEast,
HeadingEast,
HeadingSouthEast,
HeadingSouth,
HeadingSouthWest,
HeadingWest,
HeadingNorthWest
};
你可以改变你的开关语句
Heading heading = floor((trueHeadingRounded - 23) / 45);
NSString *cardinalDirection;
switch (heading) {
case HeadingNorth: cardinalDirection = @"north"; break;
case HeadingNorthEast: cardinalDirection = @"northeast"; break;
case HeadingEast: cardinalDirection = @"east"; break;
case HeadingSouthEast: cardinalDirection = @"southeast"; break;
case HeadingSouth: cardinalDirection = @"south"; break;
case HeadingSouthWest: cardinalDirection = @"southwest"; break;
case HeadingWest: cardinalDirection = @"west"; break;
case HeadingNorthWest: cardinalDirection = @"northwest"; break;
}
NSLog(@"%@", cardinalDirection);
答案 4 :(得分:0)
你可以使用类似的东西:
cardinalDirection = ( trueHeadingRounded <= 22 ? @"north" :
trueHeadingRounded <= 68 ? @"northeast" :
treuHeadingRounded <= 114 ? @"east" :
等
但是,我想我会使用映射数组建议。