我是 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"]
您可以考虑的另一种方法是使用
Tuple
或 Dictionary
.如果您使用
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/