Swift - 向数组追加元素:数组索引超出范围

3

当我试图向我的数组中添加一个项时,会出现“EXC BAD INSTRUCTION”错误,并且会显示以下信息:

fatal error: Array index out of range

这是代码:

var tabelle : [[Actions]] = [[]]

func doSomething() {

    var results = self.fetch()

    var oldProjektName: String = results[0].projektName
    var count: Int = 0

    for item in results {
        if oldProjektName == item.projektName {
           tabelle[count].append(item)               
        } else {
            count++
            tabelle[count].append(item)
        }
        oldProjektName = item.projektName
    }
}

只要 count = 0 就不会出错,但是当 count = 1 时,应用程序就会崩溃。
2个回答

6
您有一个只有一个元素的数组:var tabelle : [[Actions]] = [[]],因此 tabelle[0] 是可用的。
在使用 tabelle[1] 之前,您需要将另一个数组添加到 tabelle 中。

谢谢!将 else 语句中的 table[count].append(item) 更改为 var array: [Actions] = [item]; tabelle.append(array) 解决了问题。 - Yannick

-1
尝试

var tabelle = [[Actions]](())


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接