Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use removeObjectsInArray in swift

Tags:

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'

like image 802
yumugee Avatar asked Jan 10 '23 08:01

yumugee


1 Answers

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)
like image 126
Sulthan Avatar answered Jan 16 '23 20:01

Sulthan