Home > Enterprise >  How can I add up, then print, the values of two randomly generated numbers in Swift?
How can I add up, then print, the values of two randomly generated numbers in Swift?

Time:12-14

As part of a Swift course, I created a very simple app that displays 2 dice and a button. Whenever the user presses the "roll dice" button, 2 random numbers are generated and then the corresponding dice images are shown.

What I want to do to improve on this little app is to add a label that sums the results of the two dice together and prints the results.

For example, if the user presses the "roll dice" button and one die shows the number 3, and other die shows the number 2, I want my label to display the sum of those two dice, which in this case is 5.

My code so far:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var diceImageView1: UIImageView!
    @IBOutlet weak var diceImageView2: UIImageView!
    
    let diceArray = [
        UIImage(named: "DiceOne"),
        UIImage(named: "DiceTwo"),
        UIImage(named: "DiceThree"),
        UIImage(named: "DiceFour"),
        UIImage(named: "DiceFive"),
        UIImage(named: "DiceSix") ]
    
    @IBAction func rollButtonPressed(_ sender: UIButton) {
 
        diceImageView1.image = diceArray[Int.random(in: 0...5)]
        diceImageView2.image = diceArray[Int.random(in: 0...5)]
    
    }
    
}


I honestly don't even know where to begin. Sorry, super beginner here.

CodePudding user response:

let x = Int.random(in: 1...6)
let y = Int.random(in: 1...6)
let z = x   y

class ViewController: UIViewController {
    
    @IBOutlet weak var diceImageView1: UIImageView!
    @IBOutlet weak var diceImageView2: UIImageView!
    @IBOutlet weak var combinedLabel: UILabel!

    let diceArray = [
        UIImage(named: "DiceOne"),
        UIImage(named: "DiceTwo"),
        UIImage(named: "DiceThree"),
        UIImage(named: "DiceFour"),
        UIImage(named: "DiceFive"),
        UIImage(named: "DiceSix")
    ]
    
    @IBAction func rollButtonPressed(_ sender: UIButton) {
        let x = Int.random(in: 1...6)
        let y = Int.random(in: 1...6)
        let z = x   y
        diceImageView1.image = diceArray[x-1] // dice start counting at 1
        diceImageView2.image = diceArray[y-1] // array indices start at 0
        combinedLabel.text = "sum: \(z)"
    } 
}

CodePudding user response:

You'll want to create a UILabel (e.g. called sumLabel) similar to your dice UIImageViews and then assign variables for each random number:

let firstRand = Int.random(in: 1...6)
let secondRand = Int.random(in: 1...6)
let sumRand = firstRand   secondRand

And then assign the result to the sumLabel.text = sumRand within rollButtonPressed()

  • Related