Jermain D
Jermain D

Reputation: 45

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?

Upvotes: 0

Views: 258

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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))

Upvotes: 1

Robert Dresler
Robert Dresler

Reputation: 11140

In moment when you're trying to set element on position count + 1 your array isn't initialized, because you just define type of your array. To fix this, first create empty array

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

then you can instead of assigning element on unexisting index append new element to your array

data.append(["type" : type,
             "details" : details,
             "cost" : cost])

Upvotes: 1

Related Questions