How does one generate a random number in Apple's Swift language?

door_number_three picture door_number_three · Jun 3, 2014 · Viewed 321k times · Source

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?

Answer

John Pavley picture John Pavley · Jun 7, 2014

Use arc4random_uniform(n) for a random integer between 0 and n-1.

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).