Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Basics (retired) Control Flow For-Condition-Increment

Mike Cho
Mike Cho
570 Points

Why not <= instead of < ?

Dear folks,

Instead of using "<= todo.count" I use "< todo.count" because otherwise it would shoot over the number of values inside the array, which is in this example 5, because the increment element "index++" already adds the last value of the array to the print statement...

Am I understanding that correctly?

I am confused...gibberish coming out of mouth...

As always, thank you for your help.

Kindly, Mike

Arman Kussainov
Arman Kussainov
4,754 Points

Because the index of array starts from 0.

Your question is a bit unclear, but you seem to grasp the point you're making. Most loops will use < but it is not necessarily rare to see <= instead - just depends on what you're trying to do and how you want to express that.

An instance of using <= would be if the right-hand-side represents an index, instead of a length. In which case, you would want to include that final value. But, I'd say how you go about writing that is a matter of personal preference.

i < length is equivalent to i <= length - 1

Mike Cho
Mike Cho
570 Points

I see. I think I understand now, where I went off track. The last example was very helpful! Thank you both very much for providing me with this additional information.