Skip to content
Join us for Free for Full Access to site Content

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.

Don’t forget to subscribe to AppMakers.Dev mailing list if you love this content and want to stay tuned with recent iOS Development news, tutorials and resources.

Keep in mind that at the moment of writing this post we used Xcode 10 and Swift 5.
If anything will change in the future, it is OK, just use the new API calls for the functions mentioned in this post.

P.S. Recently AppMakers.Dev was included in the list of the Top 30 iOS Programming Blogs on Feedspot

Back To Top
Search

Get Latest App Development News, Tips and Tutorials

* indicates required


Send this to a friend