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 Class Inheritance Overriding Methods

Daniel Cohen
Daniel Cohen
5,785 Points

Code repetition in the video

We are told that we should avoid replicating code within our work. But in this video we replicate a lot of code when overriding the fireAtEnemy function just to make it not consider whether we are in range or not. It would be even more replication if the fireAtEnemy function were more complicated. Another student suggested in a previous video to modify the function to provide updates for: current enemy health, how much damage enemy was hit for, enemy health remaining, how much they were hit for the next time, enemy health remaining etc. until death and then display the enemy vanquished notification. This is why I thought about all this duplication.

I think a better way would be to override the inRange function instead to make it always return true:

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

This way we are not duplicating code. (I'm not whether we still need to pass in the position, range and target arguments into the inRange function but I couldn't remove them without getting an error.)

Indeed, we are repeating unnecessarily 5 lines of code. Regarding your question, it's still necessary to pass in the position, range and target arguments (it's part of the syntax, I believe, since you're re-declaring the function).

I like this change.