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

Dont understand repeat-while loops (Swift)

Hello Everyone,

I don't understand the difference between a repeat-while loop and a while loop. At the end of the day, they both do the same exact thing. Can someone please explain? Here is the code the video showed me how to write a loop:

var todo: [String] = ["Return Calls","Write Blogpost","Cook Dinner"]

var index = 0

while index < todo.count {
    print(todo[index])
    index++
}

index = 0

repeat {
    print(todo[index])
    index++
} while index < todo.count

1 Answer

Hello :

Yes they do the same, but their difference is that one evaluates a condition first before performing any codes, and the other one performs the code and then continues to the evaluation.

This explanation comes from the e-book "The Swift Programming Language".

  • “A while loop starts by evaluating a single condition. If the condition is true, a set of statements is repeated until the condition becomes false.”

  • “The other variation of the while loop, known as the repeat-while loop, performs a single pass through the loop block first, before considering the loop’s condition. It then continues to repeat the loop until the condition is false.”

Thank You so much! Explained it very well.