1

I m trying to create a function that could remove items such as following:

var array = [23,36,12,45,52,63]
removeItem(12,array)
result : array = [23,36,45,52,63]

I m trying to implement this for PFObject but I m getting error:

public func removeObjectFromArray(user:PFObject,array:[PFObject]) -> [PFObject]{

    for var i = 0;i < array.count ; i++ {
        if array[i].objectId == user.objectId{
            array.removeAtIndex(i)
            return array
        }
    }
}

The error that I m getting:

Immutable type of [PFObject] only ha mutating members named 'removeAtIndex'

Any solution for this?

Thank you

egor.zhdan
  • 4,555
  • 6
  • 39
  • 53
Vimlan.G
  • 193
  • 1
  • 13
  • NSMutableArray provides this https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/#//apple_ref/occ/instm/NSMutableArray/removeObjectsInArray: – danh Aug 26 '15 at 15:54

2 Answers2

0

Try doing this:

public func removeObjectFromArray(user: PFObject, array: [PFObject]) -> [PFObject] {
    var a = array
    for i in 0..<a.count {
        if a[i].objectId == user.objectId {
            a.removeAtIndex(i)
            return a
        }
    }
    return a
}

The problem is that you try to modify function argument.

You can also make function parameter mutable by adding var keyword, here is related question: Swift make method parameter mutable?

Community
  • 1
  • 1
egor.zhdan
  • 4,555
  • 6
  • 39
  • 53
0

I'm not a swift developer, but I never like to remove objects in a loop. Here's how I would do it (pseudo code):

var a = empty array
for i in (0 -> length of array) {
    if array[i].objectId != user.objectId {
        a.addObject(array[i])
    }
}
return a
AlexKoren
  • 1,605
  • 16
  • 28