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

Cory Sovilla
Cory Sovilla
11,087 Points

Syntax Question

Hello, so I was watching "High Level Overview" video in Swift 2.0 Object Oriented Language when I noticed in the code below under the function 'fireAtEnemy' why is the first paramenter not asking for 'position: self.position.. while the other two parameters 'range: self.range' and 'target:enemy.position it is needed.

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("The Enemy Escaped!")
    } 
}

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

    let availablePosition = position.surroundingPoints(withRange: range)

    for point in availablePosition {
        if (point.x == target.x) && (point.y == target.y) {
            return true
        }
    }
    return false
}

}

Thank you, Cory

1 Answer

You are asking why the parameter name doesnt appear for the first parameter? That just happens to be the convention in swift, the first parameter of a function is not displayed.

func randomFunction(param1: String, param2: String) {  }

is called as

randomFunction("lol", param2: "pengiun hats")

If you want to have the first parameter name appear, you have to name it twice basically

func funcDisplaysFirstParameterName(thisNameWillBeDisplayed param1: String, param2: String) {}

so that will be called like this

 funcDisplaysFirstParameterName(thisNameWilBeDisplayed: "LOL", param2: "see?")

Just a quirk I guess, BUT, it can serve a purpose if you name your functions right. For example

func swapString(param1: String, withString: Int) { }
swapString("First String", withString: "SecondString")

so it can be used to your advantage. But if you specifically want the first parameter name to appear you must declare a special name for it