FS.O6 FS.O6 - 18 days ago 8
Swift Question

Check duplicates properties on Swift array

I have a custom class called

Place
with 3 properties:


  • Name (
    String
    )

  • Category (
    String
    )

  • GeoPoint (
    CLLocationCoordinate2D
    )



I have an array of type
[Place]
of 100 objects and I want to check if there are duplicates on the
GeoPoint
property (just on this one).

How can I check duplicates of a specific property in an array of custom objects?

Thanks!

Answer

You can do something like this:

var dict : [String : Int] = [:]

for place in arr {
    if dict[place.GeoPoint] != nil {  // Not in dictionary
        if dict[place.GeoPoint] >= 1 { // If already there
            return true // Duplicate
        } else {
            dict[place.GeoPoint]! += 1 // Increment instance
        }
    } else {
        dict[place.GeoPoint] = 0 // Put in dictionary
    }
}

return false // No duplicates

Where you loop through a [Place] array and check to see how many have the same GeoPoint. Then check to see if there's one there more than once.

Comments