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.

Start your free trial

iOS Object-Oriented Swift 2.0 Classes Helper Methods

Lana Wong
Lana Wong
3,968 Points

I do not understand

I like to copy all these works down, so I could reference them in the future. For some reason, my code does not work.

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!")

            }
        }else {
            print("Darn! Enemy out of range!")
    }
    }

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

If you test this on Xcode, you will see the problem.

Thx!

1 Answer

The two methods should be inside the Tower class. Copy and paste fireAtEnemy() and inRange() inside the Tower class.