The Cook The Cook - 2 months ago 7x
iOS Question

How to remove common items from two struct arrays in Swift

In my app I have two struct arrays and I want to remove common items from one of them. My struct:

struct PeopleSelectItem {
var name = ""
var id = ""
var added = false

My arrays:

var people : [PeopleSelectItem] = []
var selectedPeople : [PeopleSelectItem] = []

I want to remove items from people array if they exist (compare by id) on selectedPeople array.

I tried several array filtering and converting to set but none of them worked. What can I do here?


  • Get an array of all ids in selectedPeople

    let selectedPeopleIDs = { $ }
  • Filter the items whose id is not in the array

    let filteredPeople = people.filter { !selectedPeopleIDs.contains($ }