Search code examples
swifttableviewnstableview

Fatal error: Index out of range when updating data source of table


can anyone provide clarification on why my code is throwing index out of range when i try to add an item to this array? Other answers around the web are situational based and don't provide a great understanding of how to rectify the error.

Here is the code for adding to the array -

@IBAction func refreshData(_ sender: Any) {
        let type = "type"
        let cost = dataAdded.shared.cost
        let details = dataAdded.shared.details
        let count = data?.count

        (data!)[count! + 1] = [
        "type" : type,
        "details" : details,
        "cost" : cost
            ] as! [String : String]
        self.tableView.reloadData()
    }

}

And here is the code for producing the TableView -

func numberOfRows(in tableView: NSTableView) -> Int {
        return (data?.count)!
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        let item = (data!)[row]
        let cell = tableView.makeView(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
        cell?.textField?.stringValue = item[(tableColumn?.identifier.rawValue)!]!
        return cell
    }

The array is declared like this -

var data: [[String: String]]?

Could this be an issue?


Solution

  • You need to init the array as your current declaration is nil

    var data =  [[String: String]]()
    

    and append to the array , also it's better to have a

    struct Item {
    
        let type:String
        let details:String
        let cost:String
    
    }
    

    var data =  [Item]()
    data.append(Item(type: type, details: details, cost: cost))