nested if statement in swift function

1.3k views Asked by At

The following function counts down a red to green light, then counts the reaction time for the user to hit a button after the green light is displayed.

func updateCounter() {

    timerInt -= 1
    if timerInt == 2{
        light.image = UIImage(named: "r.png")
    } else if timerInt == 1 {
        light.image = UIImage(named: "yellow.png")


    } else if timerInt == 0 {

        light.image = UIImage(named: arc4random_uniform(2) == 0 ? "no.png" : "g.png")


        timer.invalidate()
        startStop.isEnabled = true
        scoreTimer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)

    }
}

Where it states else if timerInt == 0, the user is given a random function. An image will either turn green or an "x" is displayed.

If the x is displayed, I would like the user to to have to hit a button that states game over to restart the red light sequence.

If a green light is displayed, I would like the user to have to test their reaction time.

This is how the function already runs now, except it does not change if the x is displayed. I guess I would like the function to run as follows:

if timeInt == 0 and green light is chosen
then run test reaction time

else if timeInt == 0 and x is chosen
then end reaction time and run game over button

How can I achieve this?

1

There are 1 answers

0
Coder-256 On BEST ANSWER

I am not exactly sure what you are trying to achieve, so I did my best. Try this:

func updateCounter() {

    timerInt -= 1
    if timerInt == 2{
        light.image = UIImage(named: "r.png")
    } else if timerInt == 1 {
        light.image = UIImage(named: "yellow.png")
    } else if timerInt == 0 {
        let green = (arc4random_uniform(2) == 0)

        light.image = UIImage(named: (green ? "g.png" : "no.png"))

        if green {
            // run test reaction time
        } else {
            //end reaction time and run game over button
        }

        // NOTE: Do you mean `scoreTimer.invalidate()`?
        timer.invalidate()
        startStop.isEnabled = true
        // NOTE: This time interval seems WAY too small ↓↓↓↓↓↓: it is only a millisecond!
        scoreTimer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)

    }
}

Replace the first two comments (aka lines beginning with //) with the appropriate code, and take note of the third and fourth comments.