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


This article will explain to you how to generate random numbers in the Swift language.

There are some common situations when you need to generate random values in your iOS apps such as

  • Simulating dice rolls.

  • Shuffling playing cards.

  • Create a unique ID for a user.

  • The random value from collection type.

In Swift 4.2, there are new, simple and secure ways to generate random values. Before that, there was a random function written in the C language. Today, you'll learn about the random() function that takes a range of values and as an output, it returns a randomly picked value every time.

How to use Arc4random() Function

Let's see an example of the arc4random() function

To generate a random number in Swift, you can use the arc4random() function, which generates a random number between 0 and UInt32.max. For example,

import Foundation
let randomNumber = arc4random()
print(randomNumber)

Note here: the output will be random in every case.

This will generate a random number between 0 and UInt32.max, which is a 32-bit unsigned integer with a range of 0 to 4,294,967,295.

Example

If you want to generate a random number within a specific range, you can use the following syntax.

import Foundation
let lowerRange: UInt32 = 1
let upperRange: UInt32 = 99
let randomNumber = arc4random_uniform(upperRange - lowerRange) + lowerRange
print("random number: \(randomNumber)")

Output

random number: 40

Note here: the output will be random in every case.

This will generate a random number between lowerRange and upperRange,inclusive.

Keep in mind that the arc4random() function generates a pseudorandom number, which means that it is not truly random, but appears random to most people. If you need a truly random number, you may want to consider using a different method, such as generating a random number using a hardware random number generator.

Generating random numbers

All numeric data types support the generation of random numbers within a specified range. You can specify the range of values (lower and upper) according to your requirements. Let's take a look at some examples,

Example

import Foundation

// 1

// print random value from 1 to 99
let randomInt = Int.random(in: 1...99)
print("random int: \(randomInt)")

// 2

// get a random value from -10 and below to 10
let randomSignedInt = Int.random(in: -10..<10)
print("random signed int: \(randomSignedInt)")

// 3

// get a random float value from 0 to 1. Eg: 0.5673451
let randomFloat = Float.random(in: 0...5)
print("random float: \(randomFloat)")

// 4

// get true or false randomly
let randomBool = Bool.random()
print("random bool: \(randomBool)")

Output

random int: 46
random signed int: -6
random float: 1.2532961
random bool: true

Let's understand the above example

Step 1 − Here we are generating a random Int by passing a range from 1 to 99. So it will always return a number within the same range.

Step 2 − Here, it will return a random number Int from the given range i.e. -10 to below 10.

Step 3 − Here, it will return a random float value between the given range i.e. 0 to 5.

Step 4 − Here, it will return a random Bool value that can be either true or false.

Generating Random Value From Collections

Using Swift's randomElement() method, we can obtain a random value from a

collection type. Many times you need to return random objects from your collection.

Before jumping into examples, let's note a point here. The randomElement() function returns an optional value of the collection type. It is recommended to unwrap the return value using an if-let or guard statement like the one below, since it may return a null value on occasion.

Example

We will use optional binding in all the examples. For example,

// Get a random value from an array
import Foundation
let languages: [String] = ["Java", "C/C++", "Swift", "Python", "JavaScript"]
if let randomLanguage = languages.randomElement() {
   print("randomLanguage: \(randomLanguage)")
}

Output

randomLanguage: Python

Conclusion

Before Swift 4.2, developers used the arc4random_uniform(n) function to get random values. This function is based on the C language style.

While the random() method in Swift 4.2 and higher versions make it easier for developers to generate random values securely and efficiently. As a result, we can write safer and more reliable code.

Updated on: 02-Jan-2023

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements