Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift 2.0 Classes High Level Overview

Robin Nilsson
Robin Nilsson
3,783 Points

Won't the while loop always drain the enemy's life completely?

In the method fireAtEnemy(), we have a while loop that decreases the life of the enemy by the strength of the tower in each iteration. Since the loop will continue till the enemy has no more health, is there really a purpose to this loop as currently written?

Won't the while loop always just drain the enemy's life completely? And in that case, wouldn't it make more sense to simply set enemy.life = 0 instead of bothering with the while loop at all?

2 Answers

Kelly Ford
PLUS
Kelly Ford
Courses Plus Student 7,658 Points

As I read it, the use of the while loop means that it will continue to decrease the enemy's life until it is 0. I think ideally it should be an "if"...

if enemy.life > 0 {
  enemy.decreaseHealth(self.strength)
  if enemy.life = 0 {
    print("Enemy vanquished!")
}
...

It would be an "if" inside a loop iterating for movement, but there is no movement in this simplified example

Paul Ryan
Paul Ryan
4,584 Points

I am not familiar with the code you are referring to but I assume eventually there will be some conditions within the while loop that may break the loop before the enemy's life is completely drained.