【发布时间】:2017-11-16 14:06:00
【问题描述】:
我正在使用集合视图将对象添加到名为collectiveSelection 的数组中
选择收集视图单元格(CurrentsElection)时,我想测试该对象是否存在于阵列(收集器)中是否存在。如果是这样,我想将其删除(以实现切换开/关效果)。如果它不在数组中,我想添加它。
我添加到数组中的项目属于自定义类,因此当我尝试在我的检查中使用 .index(of:) 时,这会导致我出现问题。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
currentSelection = itMachine.selection[indexPath.row] // returns some selection of type 'Attractions'
if collectiveSelection.contains(where: { $0 == currentSelection}){ // if selection exists in array, remove it, if it doesn't, add it
let itemIndex = collectiveSelection.index(of: currentSelection) // error message about .index not being available for custom class Attractions
collectiveSelection.remove(at: itemIndex)
updateCell(having: indexPath, selected: false)
} else { // deselect
collectiveSelection.append(currentSelection!)
updateCell(having: indexPath, selected: true)
}
}
我尝试让我的自定义类符合 Equatable,但这并没有帮助,因为我仍然遇到错误。关于如何在数组collectiveSelection 中获取自定义元素currentSelection 的索引的任何想法?
【问题讨论】:
-
你应该尝试使用 .index(where:) 方法,而不是检查是否包含
-
如果您发布错误所说的内容会很有帮助。
-
您可以在
collectiveSelection上使用filter来删除该元素 - 只需执行collectiveSelection.filter { $0 != currentSelection }但听起来您的问题与equals有关 -
不要使用数组。使用
Set<Attractions>。然后你可以使用containsinsert和remove,只要你的Attractions对象符合Hashable。
标签: ios arrays swift uicollectionview