Loading...

How to generate a random number in Swift?

question swift
Ram Patra Published on March 14, 2021

You can use the random method in Int struct for this.

let random:Int = Int.random(in: 1...5)

The above code will generate a random number within the closed range 1 to 5.

In closed range, both the numbers are inclusive.

let range = 1...5
print(range.contains(0)) // false
print(range.contains(3)) // true
print(range.contains(5)) // true
Ram Patra Published on March 14, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift November 16, 2023 How to check whether a value is not nil in Swift and assign it to a variable at the same time?

In Swift, there are several ways to check for nil and assign a value to a variable, depending on the context and what you want to achieve. Here are some common approaches:

question swift xcode August 12, 2020 How to remove a Swift package from a project in Xcode?

If you go to Xcode > File > Swift Packages, you can see options to add a new Swift package, update them, reset caches, and resolve package versions. However, you do not see an option to remove a particular Swift package.

question swift macOS October 29, 2023 How to make Color conform to RawRepresentable in Swift in macOS?

For various reasons you may want to convert the Color type to a String. And, below is a relatively cleaner way to do it.