In this tutorial, you are going to learn how to generate a random number in Swift programming.
Generating a random number in Swift can be done in multiple ways. In this article, I am going to mention some of the widely used methods that can help you to perform this task.
Swift 4.2 introduced SE-0202: Random Unification to make developers’ tasks easier. it provides the random()
function that can be used for generating a random number.
Now let’s see some examples in Swift for generating random numbers using the random function:
Below is a Swift program for generating a random integer type number between 1 and 10:
var randomIntNum = Int.random(in: 1...10)
print(randomIntNum)
After you run the above program you will get a random number in the range 1 through 10.
Now let’s see another example below that will generate a number in a range 1 and 9:
var randomIntNum = Int.random(in: 1..<10)
print(randomIntNum)
In the above example, we have used the <
operator. Using this operator, we are getting a random number that will be up to less than 10 i.e 9. So it generates the number which will be in the range 1 to 9.
We can also use a random float type number using the random()
function.
Below is the example:
var randFloat = Float.random(in: 1...10)
print(randFloat)
Below is the program for generating a random double type number using the Swift random()
function:
var randDouble = Double.random(in: 1...10)
print(randDouble)
For this, we have to import the Swift CoreGraphics library. Using this library, we can create floating-point scalar type values.
Now let’s see our program for generating random CGFloat:
import CoreGraphics
var randCGFloat = CGFloat.random(in: 1...10)
print(randCGFloat)
The arc4random()
function returns a random number that is between 0 and (2^32)-1. Below is the program using the arc4random():
import Darwin
var randomNum = arc4random()
print(randomNum)
The above code will return a random number ranging in 0 and (2^32)-1.
You can also set an upper range in the arc4random function up to which number you want to get the random number. It will return a number ranging from 0 to your chosen number that you pass as the argument to the function.
If we want to get a random number ranging in 0 and 10, then below is the code:
import Darwin
var randomNum = arc4random() % 10
print(randomNum)
If you use the arc4random_uniform()
function, you have to pass an argument that will be the upper limit of the random number.
Below is the code to get a random number between 0 and 50 using the arc4random_uniform function:
import Darwin
// Random number between 0 and 50
var randomNum = arc4random_uniform(50)
print(randomNum)
If we want to get a random number between our chosen range, then below is an example:
import Darwin
// Random number between 10 to 50
var randomNum = arc4random_uniform(50) + 10
print(randomNum)
The above Swift code will return a random number in the range 10 to 50.