方法不能在Switch语句中使用?

时间:2014-10-09 18:03:28

标签: ios switch-statement

为什么我不能在switch语句中使用sceneWithSize:?如果我在开关盒外面创建我的新游戏场景的对象,它可以正常工作吗?但我根据用户选择的spriteNode来切换游戏场景。为什么会发生这种情况,是否有其他方法可以做我想做的事情?

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
      /* Called when a touch begins */
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self];
        SKNode *node = [self nodeAtPoint:location];
        NSLog(@"Level Selected: %@", node.name);
        int x = [node.name intValue];

        switch (x) {
            case 1:
                 // if I move this code outside the switch statement it works?
                LevelOne *newscene = [LevelOne sceneWithSize:self.size]; // here is where I get an expected expression error?
                 //[self.view presentScene:newscene transition:[SKTransition doorsOpenVerticalWithDuration:1]];
                break;

            default:
                break;
        }
    }

1 个答案:

答案 0 :(得分:4)

这不是因为方法调用,而是因为你无法使用变量声明启动case。你必须用花括号包裹整个块,如下所示:

switch (x) {
        case 1: {
             // if I move this code outside the switch statement it works?
            LevelOne *newscene = [LevelOne sceneWithSize:self.size]; // here is where I get an expected expression error?
             //[self.view presentScene:newscene transition:[SKTransition doorsOpenVerticalWithDuration:1]];
            break;
        }

        default:
            break;
    }