iOS Build a Simple iPhone App with Swift Improving Our User Interface Random Colors

Nick Johnson
Nick Johnson
2,345 Points

Why, when setting the upper bound for the random number generator, do we not have to do colors.count - 1?

Maybe I'm wrong in thinking colors.count == 7 (in this particular case). But if that is the case, if we were to return colors[7], wouldn't that cause an out of bounds error?

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Staff

Hi there! You're right, it would. However, the nextInt returns a number between 0(inclusive) and the upperBound number (exclusive). So, in this case you will only ever get the numbers 0-6 as 7 is not included.

Here's some documentation

This is simply how the upperBound in the nextInt works.

Hope this helps! :sparkles:

Nick Johnson
Nick Johnson
2,345 Points

Got it, thanks Jennifer!