0

In my code I have four constants variables which showcase adding, subtracting, multiplying and dividing three numbers which are randomly generated values between and including 0 and 10. I have created an array called 'myQuestions' which holds all four of these variables. My question is how can i randomly access all the values in the array and take a random value in the array and put it in a label as text.

import UIKit
   
   class GameScreenViewController: UIViewController {
       @IBOutlet weak var answerTxtLabel: UITextField!
       @IBOutlet weak var questionLabel: UILabel!
    
    func updateQues() {
       let firstNum = Int.random(in: 0...10)
       let secondNum = Int.random(in: 0...10)
       let thirdNum = Int.random(in: 0...10)
       let correctAnswerForAddingNums = firstNum + secondNum + thirdNum //calculates answer for adding three numbers
       let correctAnswerForSubtractingNums = firstNum - secondNum - thirdNum //calcultes the answer for subtracting
       let correctAnswerForMultiplyNums = firstNum * secondNum * thirdNum //calculates the answer for multiply three numbers
       let correctAnswerForDividingNums = firstNum / secondNum / thirdNum // to solve: division cannot be divided by zero. make sure second and third numbers are not 0.

       let additionOfNumber = "\(firstNum) + \(secondNum) + \(thirdNum)"
       let subtractionOfNumber2 = "\(firstNum) - \(secondNum) - \(thirdNum)"
       let multiplicationOfNumber3 = "\(firstNum) * \(secondNum) * \(thirdNum)"
       let divisionOfNumber4 = "\(firstNum) / \(secondNum) / \(thirdNum)"
       let myQuestions = [additionOfNumber, subtractionOfNumber2, multiplicationOfNumber3, divisionOfNumber4]

        
        questionLabel.text = myQuestions[0]
        questionLabel.text = myQuestions[1]

        print(correctAnswerForAddingNums)
        print(correctAnswerForSubtractingNums)
        print(correctAnswerForMultiplyNums)
      //  print(correctAnswerForDividingNums)

    }
       override func viewDidLoad() {
           updateQues()
           super.viewDidLoad()
   
           

       }
AravP
  • 3
  • 2

1 Answers1

0

Arrays have a .randomElement() option. It is easy to access.

yourArray.randomElement()
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48