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
Michael touboul
3,053 Pointsindex++
Hello everyone, i understand everything except one that is very confusing.. How come that the index value changed to 5 ??? the condition is as long as index is less then the "count" (count = 5 times) keep the loop going.. index++ is incrementing the value by one to index = 1, and not to 5, so how is it possible that it equals to 5 ???? this is freaking me out, please help!!!
1 Answer
Dave Berning
17,365 PointsI hope this answers your question. It can be a little tricky to grasp sometimes. Next time, please include a code snippet or resource so it is easier to understand your question.
var index: Int = 0
let count: Int = 5
while (index < count) {
index += 1
}
/* How while loops in Swift work...
Loop 1:
index = 0
index += 1
index is now 1
0 < 5 so it is TRUE
Loop 2:
index = 1
index += 1
index is now 2
1 < 5 so it is TRUE
Loop 3:
index = 2
index += 1
index is now 3
2 < 5 so it is TRUE
Loop 4:
index = 3
index += 1
index is now 4
3 < 5 so it is TRUE
Loop 5:
index = 4
index += 1
index is now 5
4 < 5 so it is TRUE
*/
As you can see, the index variable does not equal 5 but it does loop through 5 times however. That is why in your results pane, you will see "(5 times)".
Simon Coates
28,695 PointsSimon Coates
28,695 Pointsa URL or a code snippet would help give people an appreciation of what this is about.