Crashalot Crashalot - 2 years ago 74
Swift Question

Use for loop to subtract two arrays of objects in Swift or is there a better way?

We need to subtract two arrays of CGPoint objects using Swift. Specifically, we want to find all the CGPoint objects in array A but not in array B.

Should we just loop through and manually compare elements, or is there a preferred mechanism native to Swift for doing this?

Answer Source

Some combination of filter and contains would do it:

let x = a.filter { !contains(b, $0) }

This is assuming there are no other characteristics of a and b you might exploit, such as them both being ordered (in which case it would be more efficient to walk them both in parallel).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download