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 Complex Data Structures Methods

Drew Butcher
Drew Butcher
33,160 Points

Why 'let' and not 'var"

Why did Pasan Premaratne use

let coordinatePoint = Point(x: xCoord, y: yCoord)

instead of

var coordinatePoint = Point(x: xCoord, y: yCoord)

It seems like we are redefining coordinatePoint several time which means it should be a variable not a constant.

What am i missing?

Ethan Neff
Ethan Neff
27,058 Points

a good habit it to always declare all your variables as let and only change to var when the complier yells at you. this habit will help you make sure whether or not it is good to modify that variable.

the multiple instances of coordinatePoint from the video has to deal with scope of the variables.

2 Answers

Drew Butcher
Drew Butcher
33,160 Points

While Ethan Neff suggestion is an interesting approach at determining whether to use 'let' or 'var'... I personally like to know the purpose behind what I'm doing.

Consequently, understanding how swift handles 'scope' is precisely the reason I asked this question.

So let's try again: Within the 'scope' of the function 'surroundingPointsWith' Pasan Premaratne has defined a constant that keeps getting reassigned. That seems very wrong to me. If I write the following two lines of code, xcode gets upset

let x: Int = 5
let x: Int = 10

Because one cannot redefined a constant, which makes sense.

Consequently, the only logical answer that i can see as to why one could keep defining the same constant name is that every iteration through a for loop has it's own scope.

Pasan Premaratne can you let me know if this is correct or not?

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

This is indeed correct! I'll repeat your statement so that any subsequent visitors to this post leave with the same understanding: Every iteration of a for loop (or any loop for that matter) has its own scope. If you were to create a variable here, I'm pretty sure the compiler would ask you to create a constant because you don't mutate the variable once created.