Skip to content

👩🏻‍💻 🧑🏽‍💻 Subscribe and Read us on Substack to Get Full Access to Our Posts


Generate Random numbers in Swift

In this tutorial, you will learn How to Generate Random numbers in Swift.

You will Need Mac, the latest Xcode to complete this tutorial.

Open Xcode and create a new playground titled “How to generate Radom Numbers”

Create two variables to represent the limits.

var minNumber = 0
var maxNumber = 300

Now let’s use the random() function to generate a random number between 0 and 300.

var randomNumberValue = Int.random(in: minNumber...maxNumber)

Run and see the results, now you know how to generate Random number in Swift.

We can improve our code a little bit to show values between 1 and 1000 printed in a console:

for _ in 1...1000 {
    print(Int.random(in: 1...1000))
}

Run and see the results:

If you have the array of Ints and want to get a random value out of it, you can do it with the shuffle() or shuffled() . Type these lines and Run.

var array = [18,323,34,22,9078,65]

print("array after shuffled(): \(array.shuffled())")

array.shuffle() // shuffle in place

print("array after shuffle(): \(array)")

BTW, we can use random() not only for Ints.

We can use it for Bool, Floats and Doubles too.

Just test bool randomness with these lines:

let boolRandomized = Bool.random()
print(boolRandomized)

for _ in 1...20 {
    print(Bool.random())
}

Check floats and doubles too:

for _ in 1...20 {
  
    let floatRandom = Float.random(in: 0..<79)
    print(floatRandom)

}



for _ in 1...20 {
   
    let doubleRandom = Double.random(in: 0.3...138.90)
    print(doubleRandom)

}

In this tutorial you’ve learned how to Generate Random numbers in Swift.

Back To Top
Search