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 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 Teacher

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!