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
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on March 14, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui macos September 3, 2024 Two ways to open a window programmatically in SwiftUI

SwiftUI provides an openWindow environment variable on macOS that allows you to open windows programmatically. Here’s how you can use it to open a new window when a button is clicked:

question macOS swift March 14, 2021 How to detect Escape key pressed in macOS apps?

Like Delete key, detection of Escape key press is also slightly different than detecting general key presses.

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)