如何在选择和取消选择单元格时仅保留数组中的不同元素?

How to keep only distinct elements in Array while selecting and deselecting cells?

我有一个包含不同单元格的集合视图,我希望能够 select 多个单元格。我能够这样做,但是当我单击一个已经 selected 的单元格时,相同的单元格会再次添加到数组中,从而导致重复。我想要发生的是当它被点击时它会将标签附加到数组,当它再次被点击时它会从数组中删除它。以下是我目前所拥有的。

func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    arrayOfFriendsSelected.append(arrayOfFriendsNames[indexPath.item])
    print(arrayOfFriendsSelected)
    var cell = collection.cellForItemAtIndexPath(indexPath) as! ShareCell
    cell.friendimage.layer.borderWidth = 3.0
    cell.friendimage.layer.borderColor = UIColorFromRGB("4F26D8").CGColor

    return true
}   

func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    var cell = collection.cellForItemAtIndexPath(indexPath) as! ShareCell
    arrayOfFriendsSelected.removeAtIndex(indexPath.item)
    print(arrayOfFriendsSelected)
    cell.friendimage.layer.borderWidth = 0.0

    return true
}

维护 Set 而不是 Array

声明喜欢

var setOfSelectedFriends = Set<String>()

并添加

setOfSelectedFriends.insert(arrayOfFriendsNames[indexPath.item])

要删除,请使用

setOfSelectedFriends.remove(<elementToRemove>)

您可以详细了解 Swift 集 here