Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Basics (retired) Control Flow While and Do-While Loop

incrementing index++

when you are incrementing the index++ in the for-in loop; doesn't that value change each time ONLY in the loop itself(inside the loop brackets). I thought that once the loop is over the value again goes back to 0(index = 0).

1 Answer

Chris Smith
Chris Smith
2,991 Points

Hi Raj,

You are halfway there...

In a for-in loop the index variable is only visible inside the loop. The technical term for this is "scope", I.e. the scope of the index variable is inside the loop only.

If you try to access the variable outside the loops curly braces it simply does not exist anymore.

This can get confusing if you have a second variable with the same name, for example:

var index = 5

then you have your for-in loop that uses a variable also called index, after the loop has finished index will still equal 5 because it is a completely separate variable.

I hope that helps.

Regards, Chris