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

Help !

Help !

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Keli'i Martin
Keli'i Martin
8,227 Points

What exactly do you need help with?

1 Answer

Hi Yasser,

In this challenge, you have an array and the question wants you to print out every element in the array using a while loop.

We need to print out each number in the array using a while loop and the println statement. A while loop continues to loop while a condition is, or is not, met. In this example, the end point would be reached when we've printed out every number in the array. That number can be found using the count property of the array. We start at the first position, which is element zero and print out all elements up to the last one. We can access each element with square brackets, numbers[0], then numbers[1] etc. This means we need a number that counts from zero and stops before numbers.count, so we need to create an index variable to do that. Start that index at zero, print out numbers[index] then increment index. Keep doing this while index is less than numbers.count.

One solution could look like this:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var index = 0;  // start counting from zero
while (index < numbers.count){ // stop if index isn't < count
  println(numbers[index])  // print the index element
  index++ // increment index

I hope that helps,