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 For-In Loop

I'm just confused why we use a constant in For In Loops? We are changing the output- isn't that a variable?

Jus wondering if I understand this correctly. It would seem to hold more logical weight if there were variables used in For In Loops. No?

Kevin Hamil
Kevin Hamil
8,203 Points

I get what you're asking, I'm not sure I'm following your question exactly. Could you post sample code to better clarify what you're asking?

2 Answers

Aaron Malone
Aaron Malone
15,762 Points

Each time you pass through the for-in loop, the looping constant (say, x in the loop for x in y) is created anew with the current value, rather than it being a variable whose value is updated.

It's not changing a variable, but repeating a set of instructions using a different constant value each time. Unless you introduce some other mutating variable into the loop, each trip through the loop doesn't really know anything about the previous trips.

Making the loop value constant removes some ambiguity of behavior, too. Imagine we're doing a loop through names, as in:

for n in names { ... }

What if we were to change a name while we were in that loop, like n = "Joshua"? Should that change then be reflected in the original array as well, or would n be entirely local to the loop? Most likely it would be the latter, but using a constant prevents the confusion entirely.

Thank you so much, Gentlemen. I am definitely stuck here. It's a new concept for me. I'm thinking having a better math-mind would help. Your answers are greatly appreciated.