If you want to cyclically remove elements from NSMutableArray based on the condition, you can encode the array in reverse order (from the last index to zero) and delete objects that satisfy the condition.
For example, if you have an array of integers and you want to remove numbers divisible by three, you can start the loop as follows:
var array: NSMutableArray = [1, 2, 3, 4, 5, 6, 7]; for index in stride(from: array.count - 1, through: 0, by: -1) { if array[index] as Int % 3 == 0 { array.removeObjectAtIndex(index) } }
Quoting in the reverse order ensures that the index of the elements of the array that remains to be verified does not change. Instead, in direct mode, if you delete, for example, the first element, then the element preceding index 1 will change to index 0, and you will have to take this into account in the code.
Using removeObject (which does not work with the above code) is not recommended in a loop for performance reasons, because its implementation goes through all the elements of the array and uses isEqualTo to determine whether to remove the object or not. The complexity order rises from O (n) to O (n ^ 2) - in the worst case, when all elements of the array are deleted, the array passes once in the main loop and crosses the array for each element again. Therefore, all decisions based on enumeration blocks, for-in , etc., should be avoided unless you have a good reason.
filter instead is a good alternative, and this is what I will use because:
- it is concise and clear: 1 line of code as opposed to 5 lines (including closing brackets) for index-based solution
- its characteristics are comparable to an index-based solution - it is a bit slower, but I think not so much.
This may not be ideal in all cases, because, as you said, it generates a new array, and does not work in place.