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-Condition-Increment

Sebastian Shelley
Sebastian Shelley
1,388 Points

In the For loop why can I increment i++ before print(todo[i]) unlike the while loop? Shouldn't this end the statement?

Title.

1 Answer

Jens Hagfeldt
Jens Hagfeldt
16,548 Points

Hi Sebastian.

Remember when Amit described how a for loop is constructed, he said that just like the while loop it too has the exact same three parts... an index, a condition, and an increment. The difference here is that in a for loop you have to declare all of them before you go into the loop. It is also custom to only use the letter i for the index in a for loop, but of course you can name it as you like. The body of the for loop is made up of all code between the curly braces { }. And the code you write in there use the three parameters of the for loop to iterate through the todo array. One thing to remember though is that the increment of the index that we set is always done after the code inside of the for loops body has been gone through one time. That is just how for loops work.

for var index = 0; index < todo.count; index++ {
     /* When we come inside of here the first time, our index will be zero
        since that is what we stated when we wrote the for loop. */

     println(todo[i])

     /* After all code inside of here has been run, the index will be incremented 
        by one. This will be done as many times as our index is less than the count 
        of the todo array, since that is what we stated when we wrote the for loop. */
}

I hope this helped... keep coding! :) / Jens