nicolasxviii nicolasxviii - 6 months ago 76
Swift Question

Make Quiz App Not Repeat Random Questions

I know that there are some solutions with shuffle, or something like that, but I dont know if I can apply them in my code. Can you please help me? How do I make the questions not repeat?

func RandomQuestions(){

var RandomNumber = arc4random() % 28
RandomNumber += 1

switch(RandomNumber){
case 1:
QuestionLabel.text = "Who is the Numer One Best DJ According to DJ Mag 2014?"
Button1.setTitle("Tiësto", forState: UIControlState.Normal)
Button2.setTitle("Avicii", forState: UIControlState.Normal)
Button3.setTitle("Hardwell", forState: UIControlState.Normal)
Button4.setTitle("Dimitri Vegas & Like Mike", forState: UIControlState.Normal)
CorrectAnwser = "3"
break
case 2:
QuestionLabel.text = "Who is the Only DJ that played in an Olimpic Games?"
Button1.setTitle("Avicii", forState: UIControlState.Normal)
Button2.setTitle("Tiësto", forState: UIControlState.Normal)
Button3.setTitle("Armin Van Buuren", forState: UIControlState.Normal)
Button4.setTitle("Calvin Harris", forState: UIControlState.Normal)
CorrectAnwser = "2"
break
}

/* ...more questions...* /

}

Answer

Your code needs to be reformatted, keeping it this way (the one you propose) you will end up adding huge bunchs of code every time you need to add a new question. Please consider doing it this way:

class Question{
 let question : String
 let optionA: String
 let optionB: String
 let optionC: String
 let optionD: String
 let correctAnswer: Int

 //add initializers here.
}

or

class Question{
 let question : String
 let options: [String]
 let correctAnswer: Int

 //add initializers here.
}

then

class QuestionRepository{
 private var questions: [Question]

 /// use this to load questions to be asked only once per game, this way you will end up having the order in which you will ask questions and there will be no repetitions.
 var readyToAskQuestions : [Question] {
    let shuffledQuestions = shuffle(questions)
    return shuffledQuestions
 }      

 init()
  {
    //build your harcoded 'questions' variable here 
  }

 convenience init(url: String)
 {
   //or load your questions from a file, NSUserDefaults, database sql file, from a webservice on the internet, etc.. 
 }
} 

Shuffle function stated here can be any of the stated as answers at sorting arrays in swift

Comments