## Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

### Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

# Error in Playground, not sure why?

No matter what I try to do, the Xcode playground gives me an error when I try to compile the code for this section. Only on one of the last parts. It tells me I am missing return in a function expected to return bool, for the func inRange. However the code clearly returns true or false from the for in loop, which is maybe just not going through for some reason. Here is my entire code for the class tower

class Tower { let position: Point var range: Int = 1 var strength: Int = 1 init(x: Int, y: Int) { self.position = Point(x: x, y: y) } func fireAtEnemy(enemy: Enemy) {

if inRange(self.position, range: self.range, target: enemy.position)
{
while enemy.life > 0
{
enemy.decreaseHealth(self.strength)
print("Enemy Vanquished!")
}
}
}

func inRange(position: Point, range: Int, target: Point)-> Bool
{
let availablePositions = position.surroundingPoints(attackRange: range)
for point in availablePositions {
if (point.x == target.x) && (point.y == target.y)
{ return true }
else
{ return false}}
}}

PLUS

You loop wouldn't iterate beyond the first point in availablePositions, as it exhaustively 'returns' true or false from the given evaluation. In theory, this might be intentional, but compiler probably unable to reason on this intentional type of 'exhaustiveness' -- You should use break to immediately interrupt further loop's execution.

However, for this particular function it is better to remove else clause at all and return false after the loop closing brace:

func inRange(position: Point, range: Int, target: Point) -> Bool
{

let availablePositions = position.surroundingPoints(attackRange: range)

for point in availablePositions {

if (point.x == target.x) && (point.y == target.y) {

return true
}
}

return false
}

Ivan, but shouldn't the function, in case the loop found a suitable value and returned true, return false anyway as it is not part of the loop, In other words if no value is found from the the loop then true is returned and it works just fine. But if the value is found the function should return true and return false afterwards as it is a separate statement inside the function definition?

PLUS

There's probably a misunderstanding of what the 'return' actially means. Function can't return more than once at a single call. When function returns, regardless of the return type, it is final operation of the function: nothing else happens within it after it returns. So when execution flow encounters return statement, it returns at that point and everything that happens to be below that point isn't executed.

Thanks! That makes a lot of sense! Камень с души! =)

Иван, подскажите, пожалуйста, а можно ли у Вас попросить адрес электронной почты (или Whatsapp), чтобы задать несколько вопросов касательно обучения программированию на этом сайте и в принципе. Для меня этот путь только начинается, а вы я вижу уже имеете большой опыт =) Просто мое образование никак не связано с IT и у меня нет знакомых к кому я мог обратиться с достаточно базовыми концептуальными вопросами (как мне кажется), ответ на которые гугл мне дает. Конечно не в столь поздний час, но я бы сформулировал вам вопросы и отправил бы завтра. Да и вообще было бы здорово иметь прямой контакт в этой области.

Заранее извиняюсь если просьба некорректная.

PLUS

@borislikhobabin Treehouse is a great resource for learning, though I haven't tried any similar alternatives which definitely exist. With a certain efforts and dedication you obviously can achieve a lot of progress. I'd suggest to try their Techdegree program, which you can start for free as a 1-week trial (at least that was the case 1 month ago when I had started it). I believe I am not a right person to give a professional opinion on concept aspects of IT industry, I just study the technologies that I'm interested in, using a lot of sources. Actually, google gives all answers. It always does. ;)