Random Swift

An introduction to randomizing functions in Swift

It is often necessary to add some randomness to a Swift application during development. For example if you need to fake data from a user input during a unit test or to display some dynamic placeholder text to get comfortable with your Auto-Layout.

In Swift 2 Apple provides these functions (among others )to deal with randomness:

  • arc4random()
  • drand48()
  • arc4random_uniform(UInt32)

Let’s explore these functions with some example code.

“But before we start …
let’s go to the Playground!”

To avoid many print statements please open a new Playground in Xcode. A Playground is a 2 column view where the left column is used to enter source code and the right column is displaying the source code’s value in realtime.

P.S.: I recommend to write the same function call on multiple lines to check that the return value is really random. Further down below you can see a screenshot of a Playground where I “played” with the random functions.


Returns a random number in the range of 0 to 2^32.

Good to know: If you do not a number of that super large range then you can also use the functions rand() and random() which return a random number from “just” half the range.


Returns a random double between 0.0 and 1.0

Be aware that the return value is Double and not Int! To learn more about drand48() and its “family” of similar functions check the Apple Documentation


Returns a random number between 0 and the inserted parameter minus 1.

For example arc4random_uniform(3) may return 0, 1 or 2 but not 3.

That function is the most common random function but it has one minor issue: dealing with UInt32 in Swift is not very common so a conversion to Int is normally done like in the following example:

var x = 10
x = x + Int(arc4random_uniform(3))

My Final Playground

Did I already say that Playgrounds are a great way to do quick, isolated code experiments? Especially for more experienced developers?
If not then now: Playgrounds are great!

And here is mine:

Screenshot of my Xcode Playground where I played with the functions above (please don’t mind my custom Xcode color theme)

If you like this article then I will write another one about how to generate random texts, colors and email address in Swift.