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

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.