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 Swift Functions and Optionals Functions Syntax and Parameters

Why does he use "let" instead of "var" when building a function?

Does "let" and "var" operate the same way in a function or is there a reason he's using "let" over "var"?

1 Answer

Yes, the only difference between Var (Variable) and Let (Constant) is the availability to change the value within the program. Also, I am guessing you teacher is my personal favorite, Amit! You can use the (let) for a value that you do not plan on changing the value within the program. For example: if I declare a piece of data that will be of type int that will hold my favorite number, a constant will best suite this because my favorite number will not change. He may also want to do this because values can change from time to time in more advanced programs and assigning a piece of data as a constant will ensure that the value will never change from the value that you set when you declare the constant.

//This will compile because the value of a constant can never changed, therefor you cannot assign a value to it.
let myName = "Landon"
myName = "Jacob"
//This will compile because myName is a variable, meaning the value can vary or change.
var myName = "Landon"
myName = "Jacob"

Hopefully this helps! If you have any more questions, feel free to ask!

Thanks! That helps to think of it in the context of the whole program instead of a specific function. It just confused me that Amit was using "let" within a function where you can pass in inputs and change the value, which I didn't think you could do with "let."

...and yes, Amit explains everything very well, as with all of the other teachers on treehouse for that matter.