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 swiftui swift May 29, 2022 How to open a new window in SwiftUI?

Although many things in SwiftUI are idiomatic and straightforward, showing your view in a new window needs a bit of coding to do. Hence, this short post.

question swift xcode October 8, 2023 How to get rid of 'Result of call to function is unused' warning in Swift/Xcode?

In Swift, if you encounter a “Result of call to ‘function’ is unused” warning, it means that you’re calling a function that returns a value (typically a result type, such as Result or any other type), but you’re not doing anything with the result. To get rid of this warning, you have a few options depending on the specific situation:

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.