samedi 13 juin 2020

Shuffle/Randomize Questions from an Array with no Repetition (SWIFT)

Hello!
Eng is not my main language so sorry
I've been browsing for several hours to find the right answer but seems like I can't apply it properly to my own code.
Most of the time, the answers given on stackoverflow for this problem are with Strings & Int examples and I'm struggling with the Question Type.

I'm just starting on Xcode & Swift and managed so far to make a Quiz App that works perfectly fine.

I've used shuffle but I can't find the rest of the code not to repeat questions previously asked.
What I exactly want to do : I have 7 questions for now, I want those to be asked ONCE in different orders anytime someone wants to play the Quiz.

I've got two classes in 2 other swift files.

This is my QuestionBank type with 7 questions all completed properly:

class QuestionBank {
var list = [Question]()


    init () {
        list.append(Question(questionNumber: 0, image: "a", questionText: "a", choiceA: "a", choiceB: "a", choiceC: "a", choiceD: "a", answer: 1))

And this is my Question class :

}
class Question {

    let number : Int
    let questionImage: String
    let question: String
    let optionA: String
    let optionB: String
    let optionC: String
    let optionD: String
    let correctAnswer: Int


    init(questionNumber: Int, image: String, questionText: String, choiceA: String, choiceB: String, choiceC: String, choiceD: String, answer: Int) {

        number = questionNumber
        questionImage = image
        question = questionText
        optionA = choiceA
        optionB = choiceB
        optionC = choiceC
        optionD = choiceD
        correctAnswer = answer

}

And the func to updateQuestion where I believe sh*t is supposed to happen but doesn't.

func updateQuestion() {

if questionNumber <= allQuestions.list.count - 1  {

imageView.image = UIImage(named:(allQuestions.list[questionNumber].questionImage))
QuestionLabel.text = allQuestions.list[questionNumber].question
optionA.setTitle(allQuestions.list[questionNumber].optionA, for: UIControl.State .normal)
optionB.setTitle(allQuestions.list[questionNumber].optionB, for: UIControl.State .normal)
optionC.setTitle(allQuestions.list[questionNumber].optionC, for: UIControl.State .normal)
optionD.setTitle(allQuestions.list[questionNumber].optionD, for: UIControl.State .normal)
selectedAnswer = allQuestions.list[questionNumber].correctAnswer

questionNumber += 1

allQuestions.list.shuffle()



Aucun commentaire:

Enregistrer un commentaire