应用程序在 Table 行加载时崩溃

App Crash on Table Row load

我正在从 CloudKit 中提取数据,但数据中只有一项。

一旦matchup加载,并且背景色出现在UI之前, 应用崩溃。我不明白为什么,有什么想法吗?

InterfaceController 观看:

func loadTable() {
    self.rowTable.setNumberOfRows(self.matchupArray.count, withRowType: "rows")
    let rowCount = self.rowTable.numberOfRows

    for i in 0...rowCount  {
        let row = self.rowTable.rowController(at: i) as! Rows!
        row?.matchup.setText(self.matchupArray[i])
        let colorBackground = UIColor.init(hex: self.teamColorArray[i])
        row?.groupColor.setBackgroundColor(colorBackground)
    }

}

func getData() {
    cloud.getCloudKit { (game: [GameWatch]) in
        var teamColorArray = [String]()
        var matchupArray = [String]()

        for item in game {
            teamColorArray.append(item.teamColor)
            matchupArray.append(item.matchup)
        }

        self.teamColorArray = teamColorArray
        self.matchupArray = matchupArray

        self.loadTable()
    }

}

更新:

发生崩溃,错误为 "fatal error: Index out of range"。

我不确定这是为什么,因为 matchupArray.count 是 1,rowCount 是 1。它开始迭代 for-loopi 作为0,并完成了第一次迭代,因为只有一个项目,它应该停止。但是我崩溃了,因为它又开始循环遍历,i为1,然后显然什么也没找到所以崩溃了。

崩溃发生在row?.matchup.setText(self.matchupArray[i])是运行之后。

错误在行中:

for i in 0...rowCount

... 运算符创建一个包含两个值的索引范围,因为 Swift 使用基于 0 的数组,您需要 ..< 运算符创建一个范围,不包括上限值。

因此这一行应该是:

for i in 0..<rowCount