Quickly generate random numbers in swift

Swift has a random function, build in the language core. It can be used to generate random values for float, Int, Double and Bool. The below code examples will make the usage clear

Generate random Int in swift

To generate a random int between 1 to 100 in swift we simply need to create a range between 1 and 100 and pass it to the random function something like

let randomValue = Int.random(in: 1...100)

Generate random float value in swift

For float, there are two examples provided where you can create decimal values which lie between 0 and 1 and a general case. Generating values between 0-1 comes in handy while generating random colours in swift

let floatValue = Float.random(in: 0..<1)

it will generate random float values between 0 and 1

let floatValue = Float.random(in: 1...100)

Generating random double values in swift

Similar to int and float we can also call random function to generate double values.

let doubleValue = Double.random(in: 1...100)

Random bool values

Now we have a bool values generator so no more mod(random number,2) == 0 for generating random boolean values. We can straightaway call random function

let boolValue = Bool.random()

Try this in the playground

print("Random int: \(Int.random(in: 1...100))")

print("Random float: \(Float.random(in: 0..<1))")

print("Random float: \(Float.random(in: 1...100))")

print("Random int:\(Double.random(in: 1...100))")

print("Random Bool: \(Bool.random())")

So finally no more arc4random_uniform() It sounded so low level 😀 Hope this helps!!!

A pat on the back !!


Join group of Software Professionals