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

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.