Swift out of range… with tableView[indexPath]

2019-08-24 04:17发布

I'm getting trouble with out of range error...

The error occurs in cell.creditLabel.text = numOfDays[(indexPath as NSIndexPath).row] + "days".

And if I put tableView.reloadData() after cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row]

then nothing shows up in the simulator...

How can I fix this problem..?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.nameArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : MoneyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MoneyTableViewCell", for: indexPath) as! MoneyTableViewCell


    cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row]

    cell.creditLabel.text = numOfDays[(indexPath as NSIndexPath).row] + "days"
    cell.levelLabel.text = creditArray[(indexPath as NSIndexPath).row]

    cell.layoutIfNeeded()

    return cell
}

3条回答
淡お忘
2楼-- · 2019-08-24 04:51

You need to check your arrays. From what I can see here, numOfDays have less elements then nameArray. Also, while you are there check creditArray as well :)

Also, cast to NSIndexPath is not necessary.

查看更多
Evening l夕情丶
3楼-- · 2019-08-24 05:02

Number of elements in "numOfDays" array are less than number of elements in "nameArray" array

查看更多
forever°为你锁心
4楼-- · 2019-08-24 05:15

Check that the arrays have the correct amount of items:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.nameArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : MoneyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MoneyTableViewCell", for: indexPath) as! MoneyTableViewCell


    cell.nameLabel.text = nameArray[indexPath.row]

    if numOfDays.count < indexPath.row {
        cell.creditLabel.text = numOfDays[indexPath.row] + "days"
    }

    if creditArray.count < indexPath.row {
        cell.levelLabel.text = creditArray[indexPath.row]
    }

    return cell
}

Also, I have removed the unnecessary casting of indexPath and the layoutIfNeeded (the cell will always draw again, since it is new).

查看更多
登录 后发表回答