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 For-Condition-Increment

Juan Bermudez
Juan Bermudez
2,180 Points

Why does the ++Index operator start at 0 and not 1 in this for loop?

When this loop runs, it prints the value of 0 first, instead of printing 1 The initializer is set to 0, however the ++Index should be 1? I am confused

var index: Int
for index = 0; index < 3; ++index {
    print("index is \(index)")
}
// index is 0
// index is 1
// index is 2
print("The loop statements were executed \(index) times")
// prints "The loop statements were executed 3 times"

2 Answers

Nathan Tallack
Nathan Tallack
22,159 Points

The three parameters you use in your for loop are counter, qualifier, incrementor.

  • It starts the loop with the counter value, which is 0
  • Evaluates the loop conditional, which is less than 3
  • Then does the loop printing the counter at 0
  • Completes the loop, then applies the incrementor
  • Loops and evaluates 1 is less than 3
  • Then does the loop again printing counter at 1
  • Completes the loop, then applies the incrementor
  • Loops and evaluates 2 is less than 3
  • Then does the loop again printing counter at 2
  • Completes the loop, then applies the incrementor
  • Loops and evaluates 3 is not less than 3
  • Ends the for loop

Makes sense?

The increment portion of the for loop happens at the end of the each iteration. So translated to the while loop you would get the following

var index: Int = 0

while index < 3 {
  print("index is \(index)") // index is still 0 here
  ++index // index is now 1
}