Tometoyou
Tometoyou

Reputation: 8376

Most efficient way to remove these objects

I'm trying to loop through a set of Users, and remove them from another set LostFollowers (if they exist). Users are identifiable by id.

struct LostFollower {
  let user: User
  let dateLost: Date
}

let users1: Set<LostFollower> = // …
let users2: Set<User> = // …

users2.forEach { user in
  // Need to remove anyone in the set users1, whose `user` property is equal to user
}

How can I do this? Will I need to use filter or is there a better way to do it?

Note: Set operations won't work because users1 and users2 are of different types.

Upvotes: 0

Views: 62

Answers (2)

Boa
Boa

Reputation: 417

let filtered = users2.subtracting(users1.map { $0.user })

Upvotes: 0

sushitrash
sushitrash

Reputation: 172

if i understand the question correctly, you're trying to remove elements from users1 ( set of LostFollowers ) if they exists in users2. I think you can do something like this

let filteredUser = users1.filter { follower in 
    !users2.contains(follower.user)
}

Upvotes: 1

Related Questions