简体   繁体   中英

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.

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

I agree with @sushitrash. If you have stated the problem correctly, it's as simple as:

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

    var users1: Set<LostFollower> = // ...
    let users2: Set<User> = // ...

    users1 = users1.filter {!users2.contains($0.user)}

Note that this is efficient because Set filter is efficient.

If that's not correct, then you have not described the problem correctly and you need to restate what you're trying to do.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM