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:
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.
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
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)
Generate random boolean value (True or false)
var myRandom = Bool.random() print(myRandom)
It will print true or false values randomly.