2

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?

asked Dec 9, 2016 at 22:55
17
  • 1
    I changed the phoneNumber objects name to Contact. Thanks for your help @AlexanderMomchliov Commented 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) Commented Dec 10, 2016 at 0:53
  • 1
    If you are not going to make your class NSCoding compliant you don't need to subclass NSObject Commented Dec 10, 2016 at 1:19
  • 1
    You are coding in Swift, no need to subclass NSObject unless you have a specific reason (to behave as NSObject) Commented Dec 10, 2016 at 1:24
  • 1
    If you need an instance where it is needed you can take a look at this answer stackoverflow.com/a/37983027/2303865 Commented Dec 10, 2016 at 1:28

1 Answer 1

3

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) }
answered Dec 10, 2016 at 0:18

2 Comments

Alex, I'm trying to filter by a property that the objects in both arrays have. The answer is not clear to me. Mind expanding a bit? Thanks man
Are you familiar with map/reduce/filter?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.