swiftyboi
swiftyboi

Reputation: 3221

How can I remove an object from an array using its original index path?

I have a UICollectionView in which the user can select data from cells to add to an array. I am attempting to highlight the selected cells when tapped, and un-highlight them when tapped again. In the same bit of code that highlights and un-highlights, I would like to add/remove the data from the array. I have no problem adding the data to the array, but I can't figure out how to remove it when un-highlighted.

Code here:

var removeFromList = [AnyObject]()
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {

    var cell = self.collectionView2.cellForItemAtIndexPath(indexPath)

    if cell!.tag == 0 {
        cell!.layer.borderWidth = 2.0
        cell!.layer.borderColor = UIColor.blueColor().CGColor
        removeFromList.append(objectIds[indexPath.row])
        cell!.tag = 1
    } else {
        cell!.layer.borderWidth = 0.0
        cell!.tag = 0
        removeFromList.//WHAT CAN I PUT HERE?
    }
    return true
}

Upvotes: 0

Views: 921

Answers (3)

BradzTech
BradzTech

Reputation: 2835

Because the array is being used as a list, you need to find the index before you can remove the element. Use Swift's find method:

removeFromList.removeAtIndex(find(removeFromList, objectIds[indexPath.row])!)

The problem with this method is that find does not work with AnyObject. Looping through the array and comparing each term won't work either, because AnyObject is not comparable. You need to change removeFromList and objectIds to a more specific class.

To make this code "prettier" and prevent your app from crashing when it tries to remove something not in the array, you should use an extension of the array class. Unfortunately, you'll have to make a new function for each data type.

func removeObjMyClass(inout arr: [MyClass], obj: MyClass) {
    if let index = find(arr, obj) {
        arr.removeAtIndex(index)
    }
}

removeObjMyClass(&removeFromList, objectIds[indexPath.row])

Upvotes: 0

Shamsudheen TK
Shamsudheen TK

Reputation: 31339

Use removeAtIndex(index: Int) method to remove an item

var removeFromList = [NSString]()

 if let index = find(removeFromList, objectIds[indexPath.row] as! NSString) {
     removeFromList.removeAtIndex(index)
 }

Upvotes: 2

iDhaval
iDhaval

Reputation: 3205

Use Dictionary for this:

var removeFromList = [NSIndexPath:AnyObject]()

if cell!.tag == 0 {
    cell!.layer.borderWidth = 2.0
    cell!.layer.borderColor = UIColor.blueColor().CGColor
    removeFromList[indexPath] = objectIds[indexPath.row]
    cell!.tag = 1
} else {
    cell!.layer.borderWidth = 0.0
    cell!.tag = 0
    removeFromList.removeValueForKey(indexPath)
}

Upvotes: 0

Related Questions