Objective-C 在 switch 语句中使用枚举,一个可以工作,但另一个不能
我写的一段代码遇到了一些困境。我必须根据之前的面貌和动作来确定面貌。
我为 4 个面向做了一个简单的枚举:
typedef enum directions {N,E,S,W}Facing;
然后有三个函数,每个函数都使用一个简单的 switch 语句,根据当前的面向采取操作。现在,函数turnLeft和turnRight工作得很好,但在函数move中,switch语句不会遇到任何情况,即使我确定输入了N、E、S或W。
- (Facing) turnLeft: (Facing) f
{
switch (f)
{
case N:
f = W;
break;
case E:
f = N;
break;
case S:
f = E;
break;
case W:
f = S;
break;
default:
break;
}
return f;
}
- (Facing) turnRight: (Facing) f
{
switch (f)
{
case N:
f = E;
break;
case E:
f = S;
break;
case S:
f = W;
break;
case W:
f = N;
break;
default:
break;
}
return f;
}
- (void) move:(Facing) f
{
switch (f)
{
case N:
y+1;
break;
case W:
x+1;
break;
case S:
y-1;
break;
case E:
x-1;
break;
default:
break;
}
}
因此,据我所知,所有这些开关的工作原理都是相似的,但第三个开关不起作用,前两个开关工作得很好。有谁知道可能是什么问题吗?
I have a little dilemma here with a piece of code I wrote. I have to determine a facing based on a previous facing and a move.
I made a simple enum for the 4 facings :
typedef enum directions {N,E,S,W}Facing;
And then there are three functions, each working with a simple switch statement, taking an action based on the current facing. Now, the functions turnLeft and turnRight work just fine, but in the function move, the switch statement doesn't hit any of the cases, even though I know for sure either N,E,S, or W are entered.
- (Facing) turnLeft: (Facing) f
{
switch (f)
{
case N:
f = W;
break;
case E:
f = N;
break;
case S:
f = E;
break;
case W:
f = S;
break;
default:
break;
}
return f;
}
- (Facing) turnRight: (Facing) f
{
switch (f)
{
case N:
f = E;
break;
case E:
f = S;
break;
case S:
f = W;
break;
case W:
f = N;
break;
default:
break;
}
return f;
}
- (void) move:(Facing) f
{
switch (f)
{
case N:
y+1;
break;
case W:
x+1;
break;
case S:
y-1;
break;
case E:
x-1;
break;
default:
break;
}
}
So, as far as I know, all those switches work simmilarly, yet the third one is not working, the first two work perfectly fine. Does anyone have any idea what could be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第三个 switch 语句是正确的,其他两个语句也是正确的,但我认为你的问题是它实际上没有做任何事情。您计算 y+1、x+1、y-1 或 x-1,然后丢弃结果。您是否在寻找例如
x = x+1;
?The third switch statement is correct, as are the other two, but I think your problem is that it doesn't actually do anything. You compute y+1, x+1, y-1 or x-1 and then just throw the result away. Are you looking for e.g.
x = x+1;
?