-2

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
Zin Win Htet
  • 2,448
  • 4
  • 32
  • 54

1 Answers1

1

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 Set... https://developer.apple.com/documentation/swift/set/subtracting(_:)-3n4lc

Fogmeister
  • 76,236
  • 42
  • 207
  • 306