Learn Courses My Dashboard

In Day 14 list challenge (Array count confusion)

To find a value in an array you use the syntax:

let randIndex = Int.random(in: 0…array.count-1)

Why do we need to have the -1 in the array.count? Wouldn’t the array count be the max number of items in the array and therefore ok? I tried to remove the -1 and got fatal error. Why? Is the counting off with the array.count? Do I get to a number that is not valid in the array? confused!


Array indexes begin with 0 so the first element has an index of 0, the second element has an index of 1 and so on.

So if your array has 4 elements the index values are 0, 1, 2 and 3.

In your example let say that the array contained 5 elements. So the random numbers need to be between 0 and 4 so when you determine the number of elements in an array with the .count method, you need to subtract 1 so that the upper index is not out of range.

Hope that helps.

Great question (I’m learning on this part too!)

What I’m getting from the newbie perspective is that the .count method starts counting at 1 vs. Array’s start at 0 therefore you need to subtract 1at the end with the .count method to get the same number.

let randIndex = Int.random(in: 0...array.count-1)

A better way to do this would be to use a Range rather than a ClosedRange.

What’s the difference?

A ClosedRange uses the ... operator and includes the upper bound. So for 0...array.count (when array.count == 5) you get 0 through 5, which is why you have to subtract 1 to avoid an out of bounds error.

A Range uses the ..< operator and goes up to but does not include the upper bound. So for 0..<array.count (when array.count == 5) you get 0 through 4.

Looking back at the example you have, you would do this:

let randIndex = Int.random(in: 0..<array.count)

And then you wouldn’t need to subtract 1 from the count.

1 Like

Thanks (and also thanks to all the other replies)! That made it very clear and understandable. Now I understand the array count better and why its going out of bounds.

1 Like