简体   繁体   中英

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

I'm trying to calculate the numberOfRowsInSection based on a specific category type selected on a previous screen (eg Bedroom Decor, Kitchen Items, Living Room Furniture, etc.). I've passed an index using prepareForSegue from the previous screen and have used the following to get the category type selected:

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

I am then cross referencing that category type with a vendor data structure to display all vendors of that specific category in the tableView. The following is the function to determine the 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
}

It succeeds to run, but once it gets to the vendor list screen, it crashes and the console displays 'Array index out of range'. I tested this out in a Playground and it seems to work fine.

For full context, once the correct number of rows are determined, I run the following to populate each cell:

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 arrays start to count from 0, not from 1. If you change your code to

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

you should be fine. I'm not sure why it worked in the playground, though. Maybe your vendorData was empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM