× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Removing objects from an array based on another array in Swift

Antonio Bello
Apr 22, 2015
<p>The easiest way is by using the new <code>Set</code> container (added in Swift 1.2 / Xcode 6.3):</p> <pre><code>var setA = Set(arrayA) var setB = Set(arrayB) // Return a set with all values contained in both A and B let intersection = setA.intersect(setB) // Return a set with all values in A which are not contained in B let diff = setA.subtract(setB) </code></pre> <p>If you want to reassign the resulting set to <code>arrayA</code>, simply create a new instance using the copy constructor and assign it to <code>arrayA</code>:</p> <pre><code>arrayA = Array(intersection) </code></pre> <p>The downside is that you have to create 2 new data sets. Note that <code>intersect</code> doesn't mutate the instance it is invoked in, it just returns a new set.</p> <p>There are similar methods to add, subtract, etc., you can take a look at them </p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29612968/Removing%20objects%20from%20an%20array%20based%20on%20another%20array%20in%20Swift/29613058">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus