Do you use >= or == when checking the end of an array index?

Do you use >= or == when checking the end of an array index?

Apple education uses ">=" here:

(Develop in Swift Explorations page 415.)

But "==" will suffice, yes?

The index would be caught with "==" and should never be greater than the count.

The only way it would be greater than the count (that I could think of) is if it started at some erroneous value like 1000 or something.

And so I might make a separate test for > count and then report an error message like "You shouldn't get here, how did your index get so large?"

So, when starting at zero and adding one each time, how do you test for the end of the index at count? Using "==" or ">=" and why?

Thank you for your time.


If the list is definitely not empty and initial index is definitely less than list count - then == will work as good as >=. With an empty list or initial index greater or equal to the count the == check won't work correctly.

The typical way to claim this is via precondition:

precondition(currentIndex >= 0 && currentIndex < elementList.count, "You shouldn't get here")
or just
precondition(currentIndex >= 0 && currentIndex < elementList.count)

This will trap the app if condition isn't withheld. Precondition is like an older "assert" but works in release builds as well as debug builds.

1 Like

@tera thank you. Good tips.

By the way, the textbook changed it's mind and started using "==" in the same code snippet on page 421.

Go figure.


1 Like

Interesting. I wonder if this has O(n) time complexity though, is it not?

1 Like


1 Like

Indeed. I fall into a trap that "plural == array (or a set / dictionary)".
All good with range.

1 Like

Yaeh, it's pretty great!

The exact type of indices depends on the Indices associated type of the Collection. For Array it's Range<Int>, but it can be other things, depending on the type

1 Like