Group Group Group Group Group Group Group Group Group

Generate Random Number & Update Variable Using A Button

Hopefully I am posting this in the right place. I am currently trying to polish up an app I made for HMA Random Sampling using SwiftUI. Right now, when you go into the Random Sample screen, it automatically generates a random number between 0.001 & 0.999. To get it to generate a new number though, the app has to be closed and then reopened to get it to generate a new number.

What I would like to implement is a “Generate Random Number” button that when pressed, will generate a new number and put the results in the variable so that it will then update the screen with the new random number and use that random number for any subsequent math afterwards until the app is closed or the button is pressed again.

If you can point me in the right direction of a tutorial that would cover something like this, I would greatly appreciate it as all of my searches have left me coming up empty.


Hi @jbachman, here is sample code for generating a random number with a button action that would then assign the label the value of that number. You can also do the same with a variable that would contain the number.

    @IBOutlet weak var label: UILabel! 

    var generatedNumber: Int = 0

    @IBAction func randomNumber(_ sender: Any) {

    let randomNumber = Int.random(in: 1...10)
    label.text = String(randomNumber)
    generatedNumber = randomNumber



1 Like

Quick edit to the reply: I did get everything working including having it update the other labels each time the button is pressed. Thank you again! This is something that I’ve been beating my head against the wall on for weeks now.

@gdelarosa - Thank you for the response on that. I’m assuming I could just change the type inference from Int to Double since it has to be between .001 & .999, correct? Also, would this update the label with a new number each time it is pressed?

Thanks again for the response and hope you’re having a great day!


1 Like

Hi @jbachman, awesome! Glad you got it to work and happy to hear I could help.