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

While And Do-While Loop

I need a better explanation of the correct use of While and Do-While Loop for Swift, because I don't get to understand the video.

1 Answer

Stone Preston
Stone Preston
42,016 Points

while loops run some code while a certain condition is true. do while loops run an action at LEAST once, and then continue to loop if a certain condtion is true.

you can use a while loop to do something as long as a condition is met

var score = 0
while score < 10 {

     println("The score is less than 10)

the above loop will continue to print out "the score is less than 10" for as long as the score is less than 10. since it starts at 0 and we increment it every time, the loop will stop running once the score hits 10.

a do while loop is used when you need the loop to run at least once.

// it will print at least once time, even if x is not equal to 10
do {
} while (x == 10)

the while loop is much more common than the do while loop in my experience. but even then you dont really use a while loop that much. the for in loop is probably the one that gets used most

Thanks, that helped me understand the while situation much more clearly.