0

I don't know why this error appears in the code:

    func torpedoDidCollideWithAlien(torpedo:SKSpriteNode, alien:SKSpriteNode){
        print("HIT")
        torpedo.removeFromParent()
        alien.removeFromParent()

        var aliensDestroyed = 0
        aliensDestroyed += 1

        if (aliensDestroyed > 10){ //Transition to GameOver or Success
            let transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
                let gameOverScene:SKScene = GameOverScene(size: self.size, won: true)
                self.view?.presentScene(gameOverScene, transition: transition)
            }

The error is at the line:

let transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5) //'Will never be executed'
rmaddy
  • 314,917
  • 42
  • 532
  • 579
norm
  • 11
  • 2
  • 5
  • 3
    Because `aliensDestroyed` will always be `1` and `aliensDestroyed > 10` won't be `true`? – songyuanyao Apr 20 '16 at 02:16
  • 2
    Pretty neat that the compiler can figure that out. It would be one thing if `aliensDestroyed` were a constant, but for a variable it's even more impressive. – BallpointBen Apr 20 '16 at 03:39

2 Answers2

5

You declare a new variable named aliensDestroyed with a value of 0. You then increment the value to 1.

You then check to see if the value is greater than 10. That can't ever be true. It will always be 1.

Therefore the contents of the if statement will never execute.

What you probably want is an instance variable named aliensDestroyed instead of creating a new local variable inside your torpedoDidCollideWithAlien function.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

That's not an error, it's a warning. The compiler has done analysis on your code and is telling you that the way you've written it your if statement will never be true so the statement inside the braces will never be executed.

rmaddy explained why in his answer.

Duncan C
  • 128,072
  • 22
  • 173
  • 272