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

While loop Swift

Hmmmmm???

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

 var index = 0
 while index < numbers.count {
 println(numbers[index])
 }

2 Answers

You've created an infinite loop. Your while loop will run an infinite amount of times always printing "1" because its condition will never change, as the variable "index" will always be smaller than "numbers.count", because it's always "0".

To help you understand, you're basically telling the program this: while index is less than this number, do this forever. This is what a while loop does. To exit this loop, index will have to change.

This is where the increment operator comes in use. By using index++ in your loop, you will tell index to increase every time it runs. Be sure to place it after the print line, so you don't miss that first element.

This will do two things -

  1. Index will continue to step through the numbers array, because of println(numbers[index]). This will print out each number in the array.
  2. Index will eventually become larger than numbers.count, which is the exact amount of elements in your array. This will stop the while loop right where you want it to stop.

Hope this helps you understand, feel free to ask if you have further questions.

Jon Schenck
Jon Schenck
2,028 Points

Well. Some people actually know what they're doing on here. Thanks Justin!

Happy to help.