如何避免错误索引超出范围? [英] How to avoid mistakes index out of range?

查看:131
本文介绍了如何避免错误索引超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 collectionCell 选择多个项目,但是如果我点击很多次取消选择单元格,出现错误 线程1:致命错误:索引超出范围

I try to select multiple items in collectionCell, but if i tap many times for deselect cell i get an error Thread 1: Fatal error: Index out of range

在此在 indexPath.item == 1 上的行 selectedTimeIntervalArray.remove(at:indexPath.item)

如何避免这种错误

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let selectedCell = collectionView.cellForItem(at: indexPath)

    if indexPath.item == 0 {
        selectedBackgroundColor(cell: selectedCell!)
        selectedTime = timeIntervalArray[indexPath.item]
        selectedTimeLabel.text = "Время - \(selectedTime)"
        selectedTimeIntervalArray.append(selectedTime)
    } else if indexPath.item == 1 {
        selectedBackgroundColor(cell: selectedCell!)
        selectedTime2 = timeIntervalArray[indexPath.item]
        selectedTimeIntervalArray.append(selectedTime2)
    }

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

    let deselectedCell = collectionView.cellForItem(at: indexPath)

    if indexPath.item == 0 {
        deselectedBackgroundColor(cell: deselectedCell!)
        selectedTime = ""
        selectedTimeIntervalArray.remove(at: indexPath.item)
    } else if indexPath.item == 1 {
        deselectedBackgroundColor(cell: deselectedCell!)
        selectedTime2 = ""
        selectedTimeIntervalArray.remove(at: indexPath.item)
    }

}


推荐答案

假设您选择 indexPath.item = = 1
然后执行

Let's say you select the cell at indexPath.item == 1. You do then

selectedTime2 = timeIntervalArray[indexPath.item]
selectedTimeIntervalArray.append(selectedTime2)

所以我们有: selectedTimeIntervalArray == [ ValueOfSelectedTime2]

现在,我们取消选择该项。
然后,您执行以下操作:

Now, we deselect the item. You do then:

selectedTimeIntervalArray.remove(at: indexPath.item)

在我们的案例中,您这样做:

So you do in our case:

selectedTimeIntervalArray.remove(at: 1)

索引1,真的吗?不,这会导致崩溃。因为 selectedTimeIntervalArray 只有一个项,并且它的索引为0。

Index 1, really? No, that causes a crash. Because selectedTimeIntervalArray has only one item and it's at index 0.

indexPath.item 不是您存储在数组中的对象的索引

indexPath.item is not the index of the object you stored in your array.

相反,检索首先是正确的索引:

Instead, retrieve first the correct index:

let objectToRemove = timeIntervalArray[indexPath.item]‌
let index = selectedTimeIntervalArray.index(of: objectToRemove​)

然后将其删除:

 selectedTimeIntervalArray.remove(at: index)

这篇关于如何避免错误索引超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆