D. Finna D. Finna - 9 months ago 44
Swift Question

Index out of range in cell of UITableViewController - swift

I have a UITableViewController. In the code of the tableview I want to display a "lineLabel" (which is just a blank label with a background at the bottom of the cell), if a value is equal to another value - and I got that working pretty nice!

The problem is that when I reach the bottom cell I get the index out of range error. I know why I get the error (will show you in code), but I do not know how to prevent that error and still get the same result as I do now?

Hope you can help me!

Here is my code:

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

let checkBackgroundColor = carsArray[indexPath.row + 1].componentsSeparatedByString("#")

if checkBackgroundColor[4] == finalCars[4] {
cell.lineLabel.hidden = true
} else {
cell.lineLabel.hidden = false

return cell

I get the index out of range error, because I am checking for an index that isn't there, in the
workoutsArray[indexPath.row + 1].componentsSeparatedByString("#")
part of my code. I just do not know how to do this otherwise? Anyone??

Answer Source

Check an array count before:

if carsArray.count > indexPath.row + 1 {
    // your code here

but also you MUST do the proper calculations of your tableview rows count and put it inside your override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int