Swift3 致命错误:索引超出范围(Swift 3)

Swift3 致命错误:索引超出范围(Swift 3),swift3,Swift3,我想创建一个您喜欢的应用程序,但当我单击一个按钮时,它会出错,该应用程序退出,并出现以下致命错误:索引超出范围。如何修复此错误?这是我的代码: @IBOutlet weak var legendaAzul: UILabel! @IBOutlet weak var legendaVermelho: UILabel! @IBAction func botaoAzul(_ sender: Any) { var resultadoAzul: [String] = [] let num

我想创建一个您喜欢的应用程序,但当我单击一个按钮时,它会出错,该应用程序退出,并出现以下致命错误:索引超出范围。如何修复此错误?这是我的代码:

@IBOutlet weak var legendaAzul: UILabel!
@IBOutlet weak var legendaVermelho: UILabel!

@IBAction func botaoAzul(_ sender: Any) {

    var resultadoAzul: [String] = []
    let numero1 = arc4random_uniform( 6 )

    resultadoAzul.append("Mata uma pessoa")
    resultadoAzul.append("Come um humano")
    resultadoAzul.append("Ser rico, mas morre daqui a um mes")
    resultadoAzul.append("Ser amigo do Homem - Aranha")
    resultadoAzul.append("Servir 7 anos em uma prisão violenta")

    legendaAzul.text = resultadoAzul [(Int(numero1))]
}

@IBAction func botaoVermelho(_ sender: Any) {

    var resultadoVermelho: [String] = []
    let numero2 = arc4random_uniform( 6 )

    resultadoVermelho.append("Mata você mesmo")
    resultadoVermelho.append("Come qualquer coisa")
    resultadoVermelho.append("Ser pobre, mas vive para sempre")
    resultadoVermelho.append("Ser amigo do Homem - Formiga")
    resultadoVermelho.append("Matar e comer seu cachorro")

    legendaVermelho.text = resultadoVermelho [(Int(numero2))]
}

你的主要问题是你硬编码了随机数的最大值,它太高了。您应该从数组“
count
动态获取它。而且,没有理由重复执行静态数据的
append(:)
。只需使用数组文本

@IBOutlet weak var legendaAzul: UILabel!
@IBOutlet weak var legendaVermelho: UILabel!

let resultadoAzul = ["Mata uma pessoa",
    "Come um humano",
    "Ser rico, mas morre daqui a um mes",
    "Ser amigo do Homem - Aranha",
    "Servir 7 anos em uma prisão violenta"
]

@IBAction func botaoAzul(_ sender: Any) {
    let index = Int(arc4random_uniform(resultadoAzul.count))
    legendaAzul.text = resultadoAzul[index]
}


let resultadoVermelho = [
    "Mata você mesmo",
    "Come qualquer coisa",
    "Ser pobre, mas vive para sempre",
    "Ser amigo do Homem - Formiga",
    "Matar e comer seu cachorro"
]

@IBAction func botaoVermelho(_ sender: Any) {
    let index = Int(arc4random_uniform(resultadoVermelho.count))
    legendaVermelho.text = resultadoVermelho[index]
}

您是否检查堆栈跟踪或调试堆栈跟踪以查找错误发生的位置?可以生成的最大数量
arc4random\u uniform(6)
为5–数组的最大索引为4。非常感谢,这是我制作的第一个应用程序,感谢您的帮助!!