#17: Generate Random Numbers with Swift

As you were used to do in Objective-C, you can still generate random numbers using the functions based on the RC4 cipher on Darwin platforms:

let random = arc4random()              // From 0 to Int32.max-1

let random2 = arc4random_uniform(100)  // From 0 to 99

arc4random_stir()                      // Re-initialize the random number generator with /dev/urandom

Both arc4random and arc4random_uniform will generate an uniformly distributed random number, but with different range.

But as you can see, all the arc4 functions return an Int32 result, regardless of the platform you are on.

The arc4random_buf function can be used to increase the range to the maximum allowed by the platform’s Int:

public func arc4randomInt() -> Int {
    var tmp: Int = 0
    arc4random_buf(&tmp, MemoryLayout<Int>.size)
    return tmp

On Linux and other non-darwin platforms, these functions will not be available but the usual libc functions or a custom random number generator should be used instead.

For more information on random number generators, check out this post from CocoaWithLove.

This short post is one of the Swift Bites, click the link for more!

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.