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 While and Do-While Loop

Michael touboul
Michael touboul
3,053 Points

index++

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!!!

3 Answers

Jacob Rice
Jacob Rice
15,494 Points
var index = 0
while index < 5 {
  index++
}
print(index)

In the example above, the output will be "5" and index will be 5. This is because the while loop will run when index is 4, then it will add one to index making it 5, and then not run again.

Zachary Kaufman
Zachary Kaufman
1,463 Points

I am taking Swift 2.0 not Swift so I never watched the video you are referring to, but I know that a while statement will continue to run until its condition is met. So if inside the {} there is a ++, it will continue to add until the conditions after the word while is met. So for example if

var count = 1
while count < 6 {
count++
}

the count will continue to add until it equals 5 because 5 is the highest number that is < 6. I hope this helps let me know if I can try to explain it better.

Jacob Rice
Jacob Rice
15,494 Points

Unfortunately, this is not correct. After execution, count will equal 6. This is because the code will continue to add until count is equal to 6, THEN it will stop. This is because the condition is met when count equals 5, then in runes once more making it 6, then it does not run again.

Confirmed in playground. Also, Swift 2 does not support ++ so you will need to start using count += 1 when you make the switch :D

Zachary Kaufman
Zachary Kaufman
1,463 Points

Ah okay makes sense thanks Jacob

Michael touboul
Michael touboul
3,053 Points

Thank you for your quick reply.