ios - 我在 Swift 5 中遇到索引超出范围错误

标签 ios swift

我是 swift 编程的新手,我在下面的粗体代码中遇到了一个错误,这是我在 Stack Overflow 上的第一篇文章,我试图弄清楚如何修复这个 Index out of Range 错误。任何帮助都会非常棒!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var progressBar: UIProgressView!
    @IBOutlet weak var trueButton: UIButton!
    @IBOutlet weak var falseButton: UIButton!

    let quiz = [

    ["Four + Two is equal to Six.", "True"],
    ["Five - Three is greater than One", "True"],
    ["Three + Eight is less than Ten, False"]

    ]

    var questionNumber = 0



    override func viewDidLoad() {
        super.viewDidLoad()

        updateUI()


    }

    @IBAction func answeredButtonPressed(_ sender: UIButton) {


        let userAnswer = sender.currentTitle // True, False
        **let actualAnswer = quiz[questionNumber][1]**

        if userAnswer == actualAnswer {
            print("Right!")
        } else {
            print("Wrong")
        }

        if questionNumber  + 1 < quiz.count {
            questionNumber += 1

        } else {
            questionNumber = 0
        }


        updateUI()

    }

    func updateUI() {

        questionLabel.text = quiz[questionNumber][0]
    }

}

最佳答案

欢迎来到 Stackoverflow!尝试提取 bool 字符串时出现崩溃错误索引超出范围的原因是因为 的元素索引 2 有一个字符串。

["Three + Eight is less than Ten, False"]

简单地说"在那里。
["Three + Eight is less than Ten", "False"]

您可以考虑的另一种方法是使用 TupleDictionary .

如果您使用 Tuple ,并且你犯了同样的错误,它会给你一个编译时错误,比如:

Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional



元组示例:
let quiz = [

    ("Four + Two is equal to Six.", "True"),
    ("Five - Three is greater than One", "True"),
    ("Three + Eight is less than Ten", "False")

]

let answer = quiz[2].1

正如 Paulw 所建议的,更好的方法是制作模型。像:

Quiz.swift
struct Quiz {
    /// Contains the question string.
    var question: String
    /// Consider changing this to `Bool`.
    var answer: String
}

用法:
let quiz = [
    Quiz(question: "Four + Two is equal to Six.", answer: "True"),
    Quiz(question: "Five - Three is greater than One", answer: "True"),
    Quiz(question: "Three + Eight is less than Ten", answer: "False")
]

let answer = quiz[2].answer

关于ios - 我在 Swift 5 中遇到索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60444611/

相关文章:

ios - 调用 stopDeviceMotionUpdates 时 CoreMotion 崩溃(仅限 iPad)

objective-c - 识别文件中的更改

ios - 修改按钮样式 iOS

ios - 我可以使用 AVAudioRecorder 将录音流发送到服务器吗?

html - 从 cloudkit 下载 html 文件

swift - 出现键盘时如何将 TextView 高度设置为左侧空间(Swift)

ios - ARC 不允许将 'BOOL'(又名 'bool')隐式转换为 'id'

ios - 如何从 SKScene 到 UIViewController?

swift - 传输多个字典ApplicationContext(从iPhone到Apple Watch)

从内存中删除 UIView 时,swift deinit 方法不起作用