Reputation: 1147
I have an array with Contact objects inside.
Then I have another array with Users.
class Contact: NSObject {
var name: String?
var phoneNumber: String?
var phoneNumberFormatted: String?
init(name: String, phoneNumber: String?, phoneNumberFormatted: String) {
self.name = name
self.phoneNumber = phoneNumber
self.phoneNumberFormatted = phoneNumberFormatted
}
}
class User: NSObject {
var name: String?
}
How can I remove a Contact object from the [Contact]
if I have a User in my [User]
with a matching name?
I know how to do it through loops but what is most efficient way?
Upvotes: 2
Views: 1785
Reputation: 63167
The best (most computationally efficient) way to do this for non-trivial array sizes is to precompute a set from the array you need to repeatedly search, and filter your other array, keeping elements only if they're not found in the set.
This leverages the O(1)
lookup performance of Set
. The algorithm as a whole is O(userPhoneNumbers.count + contacts.count)
let userPhoneNumbers = Set(users.lazy.map{ $0.phoneNumber })
let filteredContacts = self.contacts.filter{ !userPhoneNumbers.contains($0.phoneNumber) }
Upvotes: 3