SWIFT:计算 tableView 的 numberOfRowsInSection 时数组索引超出范围

SWIFT: Array index out of range' when calculating numberOfRowsInSection for tableView

我正在尝试根据在上一个屏幕上选择的特定类别类型(例如卧室装饰、厨房用品、客厅家具等)来计算 numberOfRowsInSection。我已经使用上一个屏幕中的 prepareForSegue 传递了一个索引,并使用了以下内容来选择类别类型:

let category = categoryData[index!]
let categoryType = category.category

然后我将该类别类型与供应商数据结构交叉引用,以在 tableView 中显示该特定类别的所有供应商。以下是确定 numberOfRowsInSection 的函数:

//pulls the data from the Category and Vendor data structures which both contain a "category" item
let categoryData = Data().headerData        
let vendorData = Data().vendorData

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    let category = categoryData[index!]
    let categoryType = category.category

    var count: Int = 0

    for (var i=1; i <= vendorData.count; i++) {

        if vendorData[i].category == categoryType {

            count = count + 1
        }
    }

    return count
}

它成功 运行,但是一旦进入供应商列表屏幕,它就会崩溃并且控制台显示 'Array index out of range'。我在 Playground 中对此进行了测试,它似乎工作正常。

对于完整上下文,一旦确定了正确的行数,我 运行 将使用以下内容填充每个单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("vendorCell", forIndexPath: indexPath) as! VendorSelectionTableViewCell

    let category = categoryData[index!]
    let categoryType = category.category

    let vendorEntry = vendorData[indexPath.row]

    if vendorEntry.category == categoryType {

        cell.vendorName.text = vendorEntry.name

    } else {
         cell.vendorName.text = "No Value"

    }

    return cell
}

Swift 数组从 0 开始计数,而不是从 1 开始。如果将代码更改为

for (var i=0; i < vendorData.count; i++) {
    if vendorData[i].category == categoryType {
        count = count + 1
    }
}

你应该没事的。不过,我不确定为什么它在操场上起作用。也许你的 vendorData 是空的。