1

I have a array of object of custom class. My class is Person. So i want to check if arrPerson contains an object then it should not be added again in array.

Here is my code

for value in data {

    if self.arrPerson.contains(where: {($0.id != value.id)}){
        self.arrPerson.append(value)
    }
}

Please tell me how can i check if object of custom class already added then it should not be added again

3
  • check stackoverflow.com/questions/37988431/… Commented Nov 30, 2017 at 8:52
  • That does not answer my question Commented Nov 30, 2017 at 8:54
  • if you don't want to compare any property you can just compare the object {($0 == value)} Commented Nov 30, 2017 at 9:13

2 Answers 2

11
if !self.arrPerson.contains(where: {($0.id == value.id)}){
    self.arrPerson.append(value)
}
Sign up to request clarification or add additional context in comments.

1 Comment

only write if !self.arrPerson.contains(where: {($0.id == value.id)}){ self.arrPerson.append(value) }
1

You can use "set" instead of array it will avoid the duplicate values.

Comments

Your Answer

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.