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 trialFrances Angulo
5,311 Pointsrole of index++ in the while loop
In the example below:
var index = 0
while index < todo.count {
println(todo[index])
index++
}
I don't understand the role of index++. I understand that it's incrementing on the var index = 0 line, but I don't understand how it works in this while loop. Here's what I read:
while the index is less than the count of todo, write the indexed items from todo. Oh and by the way, index++.
Can somebody dissect this?
3 Answers
Ed Williams
2,969 PointsIt sounds as though you understand it pretty well. The final detail to note is that as this is a while loop and without that line 'index' would always be zero and the loop would never reach an end and therefore cause your app to become unresponsive and crash. The loop says while index is less than the count of todo, run the lines of code inside the loop, each time those lines run (specifically the line in question), it increments index by 1, and there eventually causes index to be greater than todo.count and the loop exits.
Matthew Reed
Courses Plus Student 17,986 PointsThe while loop will run over and over until index is greater that the amount of todos. index++
adds one to the value inside of the index variable. so the first time the loop runs index equals 0. then next time it equals 1 and so on.
Frances Angulo
5,311 PointsSo at what point will the index be greater than the amount of todos? If the index is set to 0, and the todos run out, they'll be equal, right?
Frances Angulo
5,311 PointsOK so in theory , you could increment every other as well- this is just telling the loop what the space between each item should be. You could do something like:
index + 3
And that would get you every third item?
Ed Williams
2,969 PointsExactly! As soon as index is no longer less than todo.count, the code inside will no longer be executed and the flow of the document continues.
Note that what you've described would be written as one of these:
index = index + 3
Index += 3