Home > Mobile >  Most efficient way to remove these objects
Most efficient way to remove these objects

Time:12-27

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related