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 September 30, 2023 How to open the Settings view in a SwiftUI app on macOS 14.0 (Sonoma)?

In macOS 14.0 (Sonoma), Apple removed support for NSApp.sendAction to open the Settings view in your SwiftUI app. You now have to use SettingsLink like below:

question swift November 17, 2023 How do get the string value of an enum in Swift?

In Swift, to get the string value of an enum, you typically have a couple of approaches depending on the enum’s definition. Let’s go through them:

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.