JUSDEV JUSDEV - 1 month ago 12x
iOS Question

fatal error: Index out of range when using UITableView with multiple sections

I am trying to delete items from an array using a UITableView, however the UITableView has multiple sections and I keep getting the following error when deleting the cell

fatal error: Index out of range


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

// Delete the row from the data source
if editingStyle == UITableViewCellEditingStyle.delete {

if let table = self.table {

self.sectionItems.remove(at: [(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row])

table.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left )



Here's how I am populating the UITableView

let sections = ["One", "Two", "Three", "Four"]
var sectionItems = [ [String](), [String](), [String](), [String]() ]

func numberOfSections(in tableView: UITableView) -> Int {

return sections.count

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.sectionItems[section] as AnyObject).count


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

return sections[section]


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell

cell.textLabel!.text = self.sectionItems[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]

return cell


Does anybody know where I am going wrong ?

I tried changing

table.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left )


table.deleteRows(at: [(indexPath as NSIndexPath).section][(indexPath as NSIndexPath)]

But I get the error:

Cannot subscript a value of type '[Int]' with an index of type


You are calling remove on the wrong array. You are calling it on your sectionItems array, not the array that is contained in the sectionItems array.

You need to use the indexPath.section to retrieve the appropriate array first, then call remove: