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

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on March 14, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift August 9, 2020 How to iterate an array in reverse in Swift?

From Swift 5.0, you can use any of the following approaches to iterate an array in reverse.

question swiftui swift September 8, 2024 How to loop through an enum in SwiftUI?

In SwiftUI, looping through an enum is not directly possible without some extra work because enums in Swift don’t inherently support iteration. However, you can achieve this by making the enum CaseIterable, which automatically provides a collection of all cases in the enum.

question swiftui swift August 31, 2024 @Published in SwiftUI

In SwiftUI, the @Published property wrapper is used in combination with the ObservableObject protocol to automatically announce changes to properties of a class. This allows SwiftUI views that depend on these properties to update automatically when the data changes.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.