Eduardo Ferreira
Eduardo Ferreira

Reputation: 25

How not repeat Switch cases? (Swift)

I'm doing a Quiz Game. I booked all the questions and their answers in each "case" of a switch. I want the case to be chosen in random order, but after the person answer the question and push the button "next", the function "randomQuestions" worked again, however I do not want it to be possible to repeat the same case previously used.

func randomQuestions ()
{
    var randomNumber = arc4random_uniform(3)
    while previousNumber == randomNumber
    {
        randomNumber = arc4random_uniform(3)
    }
    previousNumber = randomNumber

    switch(randomNumber)
    {
    case 0:
        textoHideUnhide()
        questionsLabel.text = "What color is the sun?"
        button1.setTitle("Yellow", forState: UIControlState.Normal)
        button2.setTitle("Black", forState: UIControlState.Normal)
        button3.setTitle("Blue", forState: UIControlState.Normal)
        button4.setTitle("White", forState: UIControlState.Normal)
        correctAnswer = "1"
        break
    case 1:
        textoHideUnhide()
        questionsLabel.text = "What color is the moon?"
        button1.setTitle("Red", forState: UIControlState.Normal)
        button2.setTitle("Blue", forState: UIControlState.Normal)
        button3.setTitle("White", forState: UIControlState.Normal)
        button4.setTitle("Orange", forState: UIControlState.Normal)
        correctAnswer = "3"
        break
    case 2:
        textoHideUnhide()
        questionsLabel.text = "What color is the grass?"
        button1.setTitle("White", forState: UIControlState.Normal)
        button2.setTitle("Green", forState: UIControlState.Normal)
        button3.setTitle("Orange", forState: UIControlState.Normal)
        button4.setTitle("Red", forState: UIControlState.Normal)
        correctAnswer = "2"
        break
    default:
        break
}

Upvotes: 0

Views: 573

Answers (2)

Palle
Palle

Reputation: 12129

A way to avoid having the same random number multiple times, you can create an array with the numbers of the questions, which you then shuffle.

var indices = [0, 1, 2]

for i in 0 ..< indices.count {
    var temp = indices[i]
    var j = arc4random_uniform(indices.count)
    indices[i] = indices[j]
    indices[j] = temp
}

the first question is the question with the number provided at indices[0] and when the user clicks next, you ask the question at indices[1] and so on.

Upvotes: 1

vadian
vadian

Reputation: 285240

You have to put the variable previousNumber outside the method as global (instance) variable

var previousNumber = UInt32.max // declare the variable with an "impossible" value

func randomQuestions()
{
  var randomNumber : UInt32
  do {
    randomNumber = arc4random_uniform(3)
  } while previousNumber == randomNumber

  previousNumber = randomNumber

  switch(randomNumber) {
    ...

Upvotes: 0

Related Questions