如何避免错误index out of range?

How to avoid mistakes index out of range?

我尝试在 collectionCellselect 多个项目,但是如果我点击 很多次 对于 deselect cell 我得到一个 error Thread 1: Fatal error: Index out of range

selectedTimeIntervalArray.remove(at: indexPath.item) 这一行 indexPath.item == 1

如何避免这种错误

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

}

假设您 select indexPath.item == 1 的单元格。 那你做

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

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

现在,我们 deselect 项目。 那么你这样做:

selectedTimeIntervalArray.remove(at: indexPath.item)

在我们的例子中你这样做:

selectedTimeIntervalArray.remove(at: 1)

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

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

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

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

然后删除它:

 selectedTimeIntervalArray.remove(at: index)