How to generate random numbers in Swift

We can generate random numbers in Swift programming in various ways. As this is Codespeedy thus we will show multiple ways but we will start with the easiest way.

Generate random number using arc4random_uniform in Swift

We can simply use arc4random_uniform as shown in the below code snippet.

var anyRandom = arc4random_uniform(100)
print(anyRandom)

It will print a random under between 0 to 100.

We can use arc4random() too, but it may return some numbers more often. Thus we recommend you to use arc4random_uniform() instead of arc4random().

Generate random number using Int.random() in Swift

You need to insert the lower limit and upper limit as shown below:

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

We have set the lower limit as 13 and the upper limit as 20 thus it will return a random number between 13 and 20. It may also return 20.

Example:

var myRandom = Int.random(in: 13...20)
print(myRandom)

It may also return 20. So how to exclude the upper limit number from the output?

We just need to do this:

var myRandom = Int.random(in: 13..<20)

We can use <instead of .

It will prevent our program to return 20 as output.

Generate random floating numbers

This is how we can generate random floating numbers

var myRandom = Float.random(in: 1...3)
print(myRandom)

Output:

2.5156908

How to declare a float variable in Swift

Generate random boolean value (True or false)

var myRandom = Bool.random()
print(myRandom)

It will print true or false values randomly.

Also read: How to check current swift version that you are using

Leave a Reply

Your email address will not be published.