BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Check if the array of objects contains another object based on its id.

Forums > Swift

Hey guys.

I have two arrays. One is the empty one. The other one contains many objects, some of them have the same "id" parameter but different "quantity" parameter so the are unique in a way.

To the new empty array I would like to append only objects based on id, so they wont repeat. Normal .contain will include two objects with the same id but with different quantity.

How can I make that happen? Thanks for help.


this looks like it might do what you are looking for:

May not be the more efficient way of doing things and maybe someone else may have a better idea but my thinking is:

1) create new array usng the normal .contains which will bring in the values with the ID that you want but with the duplicates where you have different quantieis 2) use on the solutions in the link to remove the duplicates


Hi, you can use the contains(where: method and check based on id. If you have a lot of items, then it would make sense to use something like Set to keep tracks of IDs already added, because this is much faster than doing contains on an array.


        if let ix = paragraphs?.firstIndex(where: { $ == }) {
            paragraphs?.remove(at: ix)


Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.