To shuffle questions from the swift quiz app

Asked 2 years ago, Updated 2 years ago, 45 views

I'm a beginner who has just started programming.
I am creating a quiz application with Xcode for 4 choices.
What kind of code should I write to shuffle the questions written in CSV data?
Please teach me.
Or I would appreciate it if you could let me know the website that gives me a hint.

Specifications

This app offers quiz questions and four choices.
If the answer is correct, move on to the next question with the correct sound. If it is incorrect, the correct answer is displayed with the incorrect sound and then move on to the next question.
The current code reads CSV data sequentially, so it will not be shuffled.

CSV data is divided by ",", and each new line contains one line of data.

quiz question, choice 1, choice 2, choice 3, choice 4, answer choice number

is listed in the order shown in .

Source Code

The code for the affected areas is as follows:

import Foundation

classQuestionData{

    var question —String

    var answer 1: String
    var answer 2: String
    var answer 3: String
    var answer 4: String
    varseikai —String
    varcorrectAnswerNumber: Int

    varuserChoiceAnswerNumber—Int?

    varquestionNo—Int=0

    init(questionSourceDataArray: [String]) {
        question=questionSourceDataArray[0]
        answer1 = questionSourceDataArray[1]
        answer2 = questionSourceDataArray[2]
        answer3 = questionSourceDataArray[3]
        answer4 = questionSourceDataArray[4]

        correctAnswerNumber=Int(questionSourceDataArray[5])!
        seikai=questionSourceDataArray [correctAnswerNumber]
    }

    funcisCorrect()->Bool{
        if correctAnswerNumber == userChoiceAnswerNumber{
            return true
        }
        return false
    }
}


class QuestionDataManager {

    staticlet sharedInstance=QuestionDataManager()

    varquestionDataArray= [QuestionData] ()

    var nowQuestionIndex: Int=0

    private init() {
    }

    funloadQuestion(){
        questionDataArray.removeAll()

        nowQuestionIndex=0

        guardlet csvFilePath=Bundle.main.path(forResource: "question", ofType: "csv") else {

           print("csv file does not exist")
           return
        }

        do{
            letcsvStringData=try String(contentsOfFile:csvFilePath,
                encoding —String.Encoding.utf8)

            csvStringData.enumerateLines(invoking:{(line,stop)in
                letquestionSourceDataArray=line.components(separatedBy:",")

                let questionData=QuestionData(questionSourceDataArray:questionSourceDataArray)

                self.questionDataArray.append(questionData)

                questionData.questionNo=self.questionDataArray.count


            })
        } catchlet error {
            print("csv file read error occurred:\(error)")
            return
        }
    }

    func nextQuestion()->QuestionData?{
        if nowQuestionIndex<questionDataArray.count{
            let nextQuestion=questionDataArray [nowQuestionIndex]
            nowQuestionIndex+=1
            return nextQuestion
        }
        return nil
    }

}

There was a blog on how to do this shuffle in Google search, so
I made an extension file and wrote it in imitation of it.
I'm a beginner.
It didn't work because I didn't understand the meaning of the code itself at all.
The following is the site I used as a reference.
https://qiita.com/fumiyasac @github/items/18ae522885b5aa507ca3

swift xcode

2022-09-30 14:50

1 Answers

The linked article is for Xcode7/Swift2, and I use NSMutableArray which I don't really want to use in the Swift app, so why don't you take it as your own?

Instead of shuffling the array in advance, the idea is to randomly select the next question for each question.(It is assumed that the question after completion of the question is not required to be left in questionDataArray.Save copies if necessary, or have a separate array to save the questions after the exam.)

 func nextQuestion()->QuestionData?{
    ifquestionDataArray.isEmpty{
        return nil
    }
    let nextQuestionIndex=Int(arc4 random_uniform(UInt32(questionDataArray.count)))
    let nextQuestion=questionDataArray [nowQuestionIndex]
    questionDataArray.remove(at:nextQuestionIndex)
    return nextQuestion
}

By the way, the remove(at:) method returns deleted elements as return values, so the last three lines can also be grouped into one line.

 func nextQuestion()->QuestionData?{
    ifquestionDataArray.isEmpty{
        return nil
    }
    let nextQuestionIndex=Int(arc4 random_uniform(UInt32(questionDataArray.count)))
    return questionDataArray.remove(at:nextQuestionIndex)
}


2022-09-30 14:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.