Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Possible to retrieve uncommon list from two array in Swift?

The scenario is that I have to delete everything except selected values.
For example, I have two array as allPeople and selectedPeople.
I just need to extract unselected people list so that I can delete from Realm. Any Help?

var allPeople = ["Wayne", "Bryan", "Peter", "Jack", "Mario", "David", "Clark", "John"]

var selectedPeople = ["Peter", "Jack", "Mario", "David"]

expected result:

["Wayne", "Bryan", "Clark", "John"] // unselected people

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Naive (?) approach filtering the array

If your array is not going to grow to any huge size then you could do something like…

let unselectedPeople = people.filter { !selectedPeople.contains($0) }

This is not optimal for large arrays but for small arrays will be fine.

Another approach using Set

If all the people are unique (which they would have to be to make your logic work). You could use Set.

let unselectedPeople = Set(people).subtracting(Set(selectedPeople))

This uses the subtracting api on Sethttps://developer.apple.com/documentation/swift/set/subtracting(_:)-3n4lc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading