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

Cory Sovilla
Cory Sovilla
11,087 Points

Trying to use GKShuffledDistribution to get a "random" number

Hello, I am trying to use GKShuffledDistribution to get a "random" number that is between 0 and the last index of an array but I can't seem to figure out how to use it properly.

GKShuffledDistribution seems to give off a GKShuffledDistribution type and that is what is holding me back. I have no idea what to use that for or how to convert it.

Please post your existing code so we have something to work with :)

3 Answers

I know you are asking for a GKShuffledDistribution solution explicitly, but as no code has been provided yet and I am not sure if using GameKit makes sense here, let me show you an alternative solution using arc4random_uniform:

let array = ["One", "Two", "Three", "Four", "Five"]
let count = UInt32(array.count)

for _ in 1...10 {
    let random = Int(arc4random_uniform(count))
    print(array[random])
}
Cory Sovilla
Cory Sovilla
11,087 Points

I am at work at the moment. What I am trying to do is modify the FunFacts app in "Building A Simple iPhone App in Swift 2.0" so that when you push the button it doesn't repeat the same fact or same color.

Both facts and colors are in a array, facts are Strings and colors are UIColor.

Cory Sovilla
Cory Sovilla
11,087 Points

Also, in your eyes what instances do you use GameKit for random numbers over arc4.