【问题标题】:Shuffle/Randomize Questions from an Array with no Repetition (SWIFT)从无重复的数组中随机化/随机化问题 (SWIFT)
【发布时间】:2020-06-13 20:04:47
【问题描述】:

我已经浏览了几个小时以找到正确的答案,但似乎无法将其正确应用于我自己的代码。
大多数时候,stackoverflow 上针对此问题给出的答案是字符串和整数示例,而我正在为问题类型而苦苦挣扎。

我刚刚开始使用 Xcode 和 Swift,到目前为止,我已经成功地制作了一个运行良好的测验应用程序。

我使用了 shuffle 但我找不到其他代码不重复之前提出的问题。
我到底想要做什么:我现在有 7 个问题,我想要那些每当有人想玩测验时,以不同的顺序被问一次。

我在另外 2 个 swift 文件中有两个类。

这是我的 QuestionBank 类型,有 7 个问题全部正确完成:

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))

这是我的问题课:

}
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
 }

还有 updateQuestion 的函数,我认为 sh*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()

【问题讨论】:

    标签: arrays swift random shuffle non-repetitive


    【解决方案1】:

    每次调用updateQuestion 时,您似乎都在改组list,这似乎是这里的问题。您应该只调用一次shuffle 并一一遍历问题。要解决此问题,请从 updateQuestion 中删除 shuffle 并将其添加到 viewDidLoad 中,或者根据以下条件在 updateQuestion 中调用一次:

    if questionNumber == 1 {
        allQuestions.list.shuffle()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      相关资源
      最近更新 更多