Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all occurrences of value in Swift Array [duplicate]

Tags:

arrays

swift

So I have an array of Int's and I am trying to create a function to delete a certain value from the array. However, the removeAtIndex() function only deletes the first occurrence and the removeLast() only removes the last. I tried enumerating through the array but I end up with an Array index out of range error, possible due to the reshifting that occurs when deleting an item from the array.

  for (index, value) in connectionTypeIDs.enumerate() {
            if (value == connectionTypeToDelete){
                connectionTypeIDs.removeAtIndex(index)
            }
        }

Any ideas on how to accomplish this?

like image 442
ardevd Avatar asked Feb 03 '16 09:02

ardevd


People also ask

How do I remove all occurrences from an array?

Using Array. The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find indexes of all the elements to be removed from an array and then remove each element from the array using the splice() method.

How do you clear an array in Swift?

To create an empty string array in Swift, specify the element type String for the array and assign an empty array to the String array variable.

How do you make an array unique in Swift?

Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.


1 Answers

The quickest way is to use filter. I don't know is that answer your question but you can have a look on this:

// remove 1 from array
arr = arr.filter{$0 != 1}
like image 50
Greg Avatar answered Oct 13 '22 00:10

Greg