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

Game Development

Swift enum random value - I need to pick a random value from an enum that holds color values

I have a enum that i am trying to pull a random color from to color a shape object.

enum Color { case Blue, Green, Black, Orange, Yellow, Red, Purple }

I've read a little about arc4random_uniform but I don't know how to make it work. Eventually I'd like to assign a random color to a class that creates a shape. Maybe there is an easier way to do it?

1 Answer

Hi there,

There is an easier way to get a random number. Again I will show you how to get the number, but after that, you my have to process a little bit. Remember that IUColor takes number from 0.0 to 1.0.

So if you want, for example, R: 200, G: 150 B: 30 You will have to divide each number by 255.0.

Here is the snippet to get the random number:

import GameKit

// This will generate a number from 0-4
let newNum: Int = GKRandomSource.sharedRandom().nextIntWithUpperBound(5) 

If you want number from 1 to 5 you just do:

import GameKit

// This will generate a number from 1-5
let newNum: Int = GKRandomSource.sharedRandom().nextIntWithUpperBound(5) + 1

If you have more question, please comment.

I hope this help,

-Dan