samedi 7 décembre 2019

Swift/Xcode: trying to access local variable that gets updated in another function

I'm a beginner and I am struggling with a certain problem regarding local variables. Specifically, I am trying to make an app where I test certain fraction questions. So, I need to generate random numbers for the test and access them so that the checker function can make sure the user got the right answer. However, if I generate a new set of numbers when the user clicks "ask question", the other checker function doesn't know what those numbers are... Here is my code below:

class ViewControllerEasy: UIViewController {

@IBOutlet weak var giveQuestionOutlet: UIButton!
@IBOutlet weak var nextButtonOutlet: UIButton!
@IBAction func nextQuestionButton(_ sender: Any) {
    nextButtonOutlet.isHidden = true
    giveQuestionOutlet.isEnabled = true
    easyQuestionResponse.text = ""
    easyQuestionLabel.text = ""
    resultLabel.text = ""
}

@IBOutlet weak var easyQuestionResponse: UITextField!
@IBOutlet weak var easyQuestionLabel: UILabel!

@IBAction func easyQuestionButton(_ sender: Any) {

    let num1 = Int.random(in: 1 ..< 6)
    let num2 = Int.random(in: 2 ..< 11)


    easyQuestionLabel.text = "What percentage does \(num1) / \(num2) represent? (Round down to the closest whole number)"
}

@IBOutlet weak var resultLabel: UILabel!
@IBAction func checkButton(_ sender: Any) {

    let expectedAnswer = ((num1 * 100) / num2)
    let expectedAnswer2 = Float(expectedAnswer)
    if Float(easyQuestionResponse.text!) == round(expectedAnswer2) {
        resultLabel.text = "Great Job! Correct Answer."
        nextButtonOutlet.isHidden = false
        giveQuestionOutlet.isEnabled = false 
    }else {
        resultLabel.text = "Sorry, that is incorrect. The correct answer was: \(round(expectedAnswer2))%"
        nextButtonOutlet.isHidden = false
        giveQuestionOutlet.isEnabled = false
    }
 }

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
    return string.rangeOfCharacter(from: invalidCharacters) == nil
}

override func viewDidLoad() {
    super.viewDidLoad()

}

}

So, how can I generate new questions when the user clicks the button to ask for it and also make sure that the code can check whether or not the user got the right answer? I tried looking at using a global variable, but that would keep the values same after the first execution of the random numbers call. Thus, I hope someone can help me with this problem. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire