I have two arrays like this:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
As you can see, James
and Steve
match and I want to be able to remove them from arrayA
. How would I write this?
Remove elements using indexes array:
Array of Strings and indexes
Array of Integers and indexes
Remove elements using element value of another array
Arrays of integers
Arrays of strings
I agree with Antonio's answer, however for small array subtractions you can also use a filter closure like this:
Like this:
The easiest way is by using the new
Set
container (added in Swift 1.2 / Xcode 6.3):If you want to reassign the resulting set to
arrayA
, simply create a new instance using the copy constructor and assign it toarrayA
:The downside is that you have to create 2 new data sets. Note that
intersect
doesn't mutate the instance it is invoked in, it just returns a new set.There are similar methods to add, subtract, etc., you can take a look at them
Original answer
This can also be implemented as a minus func:
Now you can use
Updated implementation for Swift 5
@francesco-vadicamo's answer in Swift 2/3/4+