How to generate a random number in Swift?

question swift
Ram Patra Published on March 14, 2021
Xcode 6.0.1+

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 macOS swift August 6, 2020 How to keep an app's window always on top of others in Swift?

Before launching the window, just use the appropriate window level, and you’re done.

question macOS swift August 14, 2020 How to quit or close an app in macOS using Swift?

You can quit or exit an app with:NSApp.terminate(self)

question macOS swift March 14, 2021 How to ignore mouse events in a view or window in macOS?

You can ignore mouse events in a window/view by adding just a single line of code.