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

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.

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

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

>Solution :

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)
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