user2741735
user2741735

Reputation: 41

Fetch Data from Core Data

I'm getting data from core data and saving it inside an array. This array is collection of dictionary. However there are duplicate dictionary inside the array. How do I filter these duplicate dictionaries inside the nsarray in Swift?

Thanks In Advance.

Upvotes: 0

Views: 119

Answers (2)

Tommie C.
Tommie C.

Reputation: 13181

How do I filter these duplicate dictionaries inside the nsarray in Swift?

Old way from ObjC still works with Swift ~ You take advantage of the properties of a set. Add the values you want into a Set. You can use the contains method to verify whether the key exists before adding it to the set. Since a Set can only contain unique values it will filter the duplicates. When finished check out the allobjects on the Set object.

A second option would be to use either the map or the filter function on the array with some comparative logic or some other criterion to define uniqueness (I don't know your precise data set so it's hard to give a relevant sample but generally you can see this article on UseYourLoaf). If you are using Swift 2.2+ you can try the forEach function available on the collections.

Other References:

Search SO for keywords Swift Set

Search SO for keywords Swift Array

Swift Set To Array On SO

Swift Collection Types on Apple Developer

Swift Official Documentation Book from Swift.org

Upvotes: 0

jsw324
jsw324

Reputation: 812

If you know the number of duplicate dictionaries you can try a counter variable. Then a simple 'if' statement i.e. if counter == 1 { //do something }

Upvotes: 0

Related Questions