SwiftDeveloper SwiftDeveloper - 3 months ago 11
Swift Question

Swift Collection view didSelectItemAtIndexPath when clicked add / remove in array

I have swift collection view and have items , i want to add each item clicked to array and same item when clicked again will be remove in array. My codes here.

My array

var services = [""]


My didSelectItemAtIndexPath codes

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


let clickeditem = items[indexPath.section].services[indexPath.item - 1]
print(clickeditem) // here clicked item this item will be add to services array when first click, after clicked again will be remove in services array


}



clickeditem // will be add to services array when first click, after clicked again will be remove in services array

Answer

You could use a struct, so:

struct Item {
    let indexPath: NSIndexPath 
    let value: AnyObject
}

services.append(Item(indexPath, value: clickeditem))

and then to remove you can iterate and check the element with that indexPath:

for item in services {
    if item.indexPath == indexPath {
        //remove your item and whatever you want
    }
}