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

Jan Francírek
Jan Francírek
1,766 Points

Given an array of numbers, print out each number in the array using a while loop and the println statement.

I have there

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I do not understand why I have to use "while" instead of "do"... I tried only to write do{println(numbers)} while numbers = 1...10

I know it does not have a sense, so I ask you for a help please.

Thank you

5 Answers

Ben Griffith
Ben Griffith
5,808 Points

Hey, just answered this in another thread so I hope you don't mind it's a copy / paste job!

So in order to iterate through our array, we need to create a counter which will also act as the index that will keep track of how many times we've looped.

var index = 0

Next step is to build the while loop. In this task, we want to loop over all the values. We can use count method of the array in order to make sure we only loop as many times as needed.

while index < nameOfArray.count {

}

If you ran this, the loop would run forever. To fix this we need to include the index and increment it by 1.

while index < nameOfArray.count {

   index++
}

Finally add your print statement inside the loop - use the index to target the correct value within the array.

while index < nameOfArray.count {

   println( nameOfArray[index] )

   index++
}
Henry Moran
Henry Moran
10,516 Points

Ben Griffin that's for such a detailed explanation of this solution. More answers should be this way. :thumbsup:

Jonathan Moore
Jonathan Moore
10,096 Points

I agree I've been stuck on this for ages now it all clicked!

whats wrong with my code

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var index = 0

while index < numbers.count { println( numbers[index] ) index ++ }

whats wrong with my code

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var index = 0

while index < numbers.count { println( numbers[index] ) index ++ }