You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中点击正确答案后切换questions数组下一个元素的实现方法

你只需要新增一个属性记录当前答题的索引即可,修改后的完整代码如下:

// 存储题目数组
var questions:[EasyQuestions] = [
    EasyQuestions(question: "1 + 1", optionA: "5", optionB: "2", hint: "3-1", correctAnswer: 1),
    EasyQuestions(question: "2 + 2", optionA: "4", optionB: "3", hint: "5-1", correctAnswer: 0)
].shuffled()
// 新增:记录当前题目索引,初始为0
var currentQuestionIndex = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // 改用动态索引获取题目
    configure(with: questions[currentQuestionIndex])
}

@IBAction func buttonClicked(_ sender: UIButton) {
    if sender.tag == questions[currentQuestionIndex].correctAnswer {
        print("The answer is correct")
        // 答对后索引+1,准备加载下一题
        currentQuestionIndex += 1
        // 判断是否还有未做的题目,避免数组越界崩溃
        if currentQuestionIndex < questions.count {
            // 加载下一题
            configure(with: questions[currentQuestionIndex])
        } else {
            // 所有题目都做完的逻辑,可自定义
            print("所有题目已完成")
        }
    }
}

func configure(with question: EasyQuestions){
    self.Question.text = question.question
    self.button1.setTitle(question.optionA, for: .normal)
    self.button2.setTitle(question.optionB, for: .normal)
}

这里加了数组越界判断,避免所有题目做完后再访问不存在的数组索引导致闪退,你可以根据自己的需求修改全部答完后的交互逻辑,比如弹出完成提示、返回上一页等。

内容的提问来源于stack exchange,提问作者Bon Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:06:05