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

Matt Brown
Matt Brown
7,782 Points

While Loop Objective...anyone know where I went wrong?

Help! Thanks :)

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

while numbers < 11 {
  println(numbers)}

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Matt,

A while loop will run forever unless we explicitly give it a condition that stops it from looping, we can do this by setting another variable which in the example below I've called count but you can call it anything you want. Each time the loop executes we retrieve one of the values from the numbers array and increment the count variable by one.

Once the count variable reaches 10 the condition will be met and the while loop will stop executing.

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

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

Happy coding!

Matt Brown
Matt Brown
7,782 Points

Ahh thats right forgot about having to end it manually with the count variable. Thanks for the speedy answer :)