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