yumugee yumugee - 4 months ago 74
Swift Question

how to use removeObjectsInArray in swift

I have two arrays

var availableIndex: Int[] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]
var answerIndex: Int[] = [1, 3, 10, 8]


I want to remove 1, 3, 10, 8 from availableIndex array. I've seen the documentation how to achieve that using removeObjectsInArray

availableIndex.removeObjectsInArray(answerIndex)


but I can't use that method, it gave me an error. I have no idea where's my fault. Sorry if my bad English

edit:

here is the error 'Int[]' does not have a member named 'removeObjectsInArray'

Answer

The proper Swifty way to do this is

availableIndex = availableIndex.filter { value in
   !answerIndex.contains(value)
}

(will create a new filtered array only with values not contained in answerIndex)

Of course, a better solution would be to convert answerIndex into a Set.

removeObjectsInArray is defined only on Obj-C mutable arrays (NSMutableArray).

An Obj-C workaround is to define the array directly as NSMutableArray

var availableIndex: NSMutableArray = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]
var answerIndex: Int[] = [1, 3, 10, 8]

availableIndex.removeObjectsInArray(answerIndex)
Comments