Issue filtering out an array of strings from Set | Swift

I would like to filter out an array of strings removeArray from a Set mySet that contains those string values :

struct ListStruct: Codable, Hashable {
    let id: Int
    let name: String
}

var mySet: Set<ListStruct> = []
mySet = Set(initialArray)

let removeArray = removeSet{$0.name}

Filtered Out

How can I properly filter out removeArray from mySet? Below is my attempt, not quite sure how to handle the array of string values.

mySet = mySet{$0.id != removeArray.contains($0)}

Solution 1:

It looks like you might be looking for something like this:

let mySet: Set<ListStruct> = [.init(id: 0, name: "name 1"),.init(id: 1, name: "name 2"),.init(id: 2, name: "name 3"),.init(id: 3, name: "name 4")]
let namesToFilter = ["name 2","name 4"]
let result = mySet.filter { !namesToFilter.contains($0.name) }
print(result)

Which would leave the items with "name 1" and "name 3".

This works by doing a filter and checking to see if the namesToFilter contains an element with an equal name property.

Similarly, if you wanted to test the id property instead:

let mySet: Set<ListStruct> = [.init(id: 0, name: "name 1"),.init(id: 1, name: "name 2"),.init(id: 2, name: "name 3"),.init(id: 3, name: "name 4")]
let idsToFilter = [0,2]
let result = mySet.filter { !idsToFilter.contains($0.id) }
print(result)