0

Objective: I have to delete object from array which has same title, vicinity, coordinate.latitude and coordinate.longitude

    class Place {
        var placeID: String?
        var title: String?
        var vicinity: String?
        var detailsUrl: String?
        var openingHours: OpeningHours?
        var position: [Double]

        var coordinate: CLLocationCoordinate2D {
          return CLLocationCoordinate2DMake(position.first ?? 0, position.last ?? 0)
    }

One way i have tried that -

extension Array {
    func removingDuplicates <T: Hashable>(byKey key: (Element) -> T) -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}


let array = list.removingDuplicates(byKey: { "\($0.coordinate.latitude)" + "\($0.coordinate.longitude)" + ($0.title ?? " ") + ($0.vicinity ?? " ") })

But i really don't like above solution. What is the most appropriate way to handle it ?

Tariq
  • 9,861
  • 12
  • 62
  • 103
  • 3
    I would check if the item exists **before** inserting it, if possible. Or use a set anyway. And add a custom implementation of `Equatable` – vadian May 27 '19 at 08:47
  • Are places with same title/vicinity/coordinates *generally* considered equal, or only in this particular context? – Martin R May 27 '19 at 09:10
  • Have a look here https://stackoverflow.com/a/55684308/2907715 – ielyamani May 27 '19 at 14:46

1 Answers1

1

Add Equatable to the Place class

class Place: Equatable {
    static func == (lhs: Place, rhs: Place) -> Bool {
        return lhs.title == rhs.title && lhs.vicinity == rhs.vicinity &&
            lhs.coordinate.latitude == rhs.coordinate.latitude && lhs.coordinate.longitude == rhs.coordinate.longitude
    }
    //...        
}

And filter the array elements with the place/places to delete

var list = [Place]()
//Delete multiple places
let placesToDelete = [Place]()
let result = list.removeAll { placesToDelete.contains($0) }
//Delete one place
let placeToDelete = Place()
let result = list.removeAll { $0 == placeToDelete }
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70