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 Basics (retired) Control Flow Comparison and Logical Operators

Confused

why do we use the let constant for for/switch... but we use variables in if statements

1 Answer

Marissa Amaya
Marissa Amaya
11,782 Points

It's essentially the difference between a loop and a conditional statement.

Loops (ex. for-in, while, do-while, for-condition-increment) Loops iterate through a data structure (like an array). Because of this, he's keeping the data structure (array) constant for the loop. This isn't a hard rule, though. There are many cases where the data structure can be a regular variable, that way it can be modifiable later on in the code. This all depends on your program, however, and what you're trying to accomplish with the data. If you're filling your array with data that shouldn't be modified, then of course declare it as a constant. If you want to be able to access and update the array as needed, then declaring it as a regular variable is perfectly fine.

Conditional Statements (ex. if, if/else, switch) The only purpose of a conditional statement is to test whether a given condition is true or false, and branch your program based off of this outcome. Like loops, conditional statements can take both regular variables and constants. However, it's more uncommon to use constants with conditional statements because the constant will be, well, constant, eliminating the need to branch the code in the first place.

For instance, in his example: ```var distance = 5,

he leaves the variable "distance" modifiable, so he can show how different values will produce different outputs in his subsequent if/else statements.

If this variable was a constant:
```let distance = 5,

then the distance would always be 5, making the if/else statements pointless since the code will only ever produce the same output. Sure, you could manually modify the constant yourself. But, this defeats the whole point of programming, which is to make the computer modify the variables for you.

Anyway, I know this was probably more than you were looking for but hope this helps nonetheless.