Generating random numbers in Swift is easy and requires only a single line of code. There are a few approaches, though. In this episode of Swift Fundamentals, we look at two options to generate a random number using Swift.

random(), random(in:), and random(in:using:)

The easiest option is to use the random(in:) and random(in:using:) methods. Fire up Xcode and create a playground by choosing the Blank template of the iOS > Playground section.

Generating Random Numbers in Swift

Add an import statement for Foundation and invoke the random(in:) method on the Int struct. The random(in:) method accepts a Range as an argument. As you may have guessed, the range defines the range for the random number.

import Foundation

Int.random(in: 10...20)

In this example, the random(in:) method returns an integer between 10 and 20 with 10 and 20 included. We can use a one-sided range to exclude 20.

import Foundation

Int.random(in: 10..<20)

Most of the number types in Swift define the random(in:) method, including Int, Int16, Int32, Float, and Double.

import Foundation

Int.random(in: 10...20)
Int16.random(in: 10...20)
Int32.random(in: 10...20)
Float.random(in: 10...20)
Double.random(in: 10...20)

Bool also defines a random() method, but it doesn't accept a Range object as an argument. That isn't surprising since the only possible values are true and false.

Bool.random()

The random() and random(in:) methods accept an optional random number generator, an object conforming to the RandomNumberGenerator protocol. The random number generator parameter is an in-out parameter. What Are In-Out Parameters in Swift covers in-out parameters in more detail.

I don't use this very often, but it can be useful if you want to explicitly define the source of randomness. If you don't specify a random number generator, the Standard Library use the SystemRandomNumberGenerator struct.

arc4random_uniform

The random(), random(in:), and random(in:using:) methods were introduced in a later version of the Swift language and the easiest way to generate a random number before these methods were available was the arc4random_uniform() function. The function is easy to use.

The arc4random_uniform() function takes one argument, the upper bound of the range the random number falls in. In this example, we generate a random number between 0 and 20, 20 not included.

arc4random_uniform(20)

To generate a random number between 20 and 30, you set the upper bound to 11 and add 20 to the result.

arc4random_uniform(11) + 20

What's Next?

The arc4random_uniform() function is less flexible, and it always returns an Int. Most of the time, I reach for the random(), random(in:), and random(in:using:) methods.