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?
-
1I changed the phoneNumber objects name to Contact. Thanks for your help @AlexanderMomchliovWalker– Walker2016年12月10日 00:19:07 +00:00Commented Dec 10, 2016 at 0:19
-
1@Walker Is there any reason to make it a NSObject? Otherwise you shouldn't. Also if the fields are required you should use let, make it non optional and add a required initializer for the property(ies)Leo Dabus– Leo Dabus2016年12月10日 00:53:45 +00:00Commented Dec 10, 2016 at 0:53
-
1If you are not going to make your class NSCoding compliant you don't need to subclass NSObjectLeo Dabus– Leo Dabus2016年12月10日 01:19:12 +00:00Commented Dec 10, 2016 at 1:19
-
1You are coding in Swift, no need to subclass NSObject unless you have a specific reason (to behave as NSObject)Leo Dabus– Leo Dabus2016年12月10日 01:24:52 +00:00Commented Dec 10, 2016 at 1:24
-
1If you need an instance where it is needed you can take a look at this answer stackoverflow.com/a/37983027/2303865Leo Dabus– Leo Dabus2016年12月10日 01:28:19 +00:00Commented Dec 10, 2016 at 1:28
1 Answer 1
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) }