首页 > 解决方案 > 如何将用户输入与 Array 的洗牌对象进行比较

问题描述

我有一堆与我的自定义类问题相关的问题

class QuestionBank {
    var list = [Question]()


    init() {
        // Creating a quiz item and appending it to the list
        let item = Question(text: "2² = ", correctAnswer: 4)

        list.append(item)

        list.append(Question(text: "3² = ", correctAnswer: 9))
        list.append(Question(text: "4² = ", correctAnswer: 16))
        list.append(Question(text: "5² = ", correctAnswer: 25))

        // and so on...
    }
}

这是这个自定义类问题

let answer : Int
let questionText : String

init(text : String, correctAnswer : Int) {
    questionText = text
    answer = correctAnswer
}

我有一个按钮,当你按下它时,所有问题(等于 QuestionBank)正在被洗牌。接下来,用户输入他的答案

@IBAction func truePressed(_ sender: Any) {
    allQuestions.list.shuffle()
    questionLabel.text = allQuestions.list[questionNumber].questionText
    if Int(textField.text!) == allQuestions.list[questionNumber].answer {
        print("yes")
    }
    textField.text = ""
}

问题是控制台不输出任何东西。我认为这是因为当 shuffle() 发生时,“questionText”和“answer”都在改组,或者我错了?如果我是对的,我该如何更改“allQuestions”随机播放,以便在按下按钮时 textField 读取用户输入,然后将 input(textField.text) 与“allQuestions.list[questionNumber].answer”进行比较?

标签: swift

解决方案


推荐阅读