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

Jon Schenck
Jon Schenck
2,028 Points

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

I have no idea how to solve this. I have been playing around trying to figure this out and need assistance.

while_loops.swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Jon Schenck
Jon Schenck
2,028 Points

Thank you for your help Dan

2 Answers

Hope that helps.

     let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   // this is the array 
       var index = 0; // this variable will be the starting point 
// the condition inside of the loop is saying until the start point is less that the array size print

    while(index < numbers.count){

    println(numbers[index]); 
 // so if the index was 1 ; 1 is less than 10 the size of the array than it would display the value of number[1] which is 2 

     index++; // then increment by 1 which means re-execute this code again
    }
Jon Schenck
Jon Schenck
2,028 Points

Thank you for your help Meek

Review while loops, they nearly always look like something like this:

var count = 0
while count < n {  // set n to the length of the array

   //some code...

   count++
}