如何从具有多个条件的数组中删除重复项?

时间:2019-05-27 08:44:10

标签: ios arrays swift sorting hash

目标:我必须从数组中删除具有相同标题,附近,coordinate.latitude和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)
    }

我尝试过的一种方式-

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 ?? " ") })

但是我真的不喜欢上面的解决方案。处理它的最合适方法是什么?

1 个答案:

答案 0 :(得分:1)

Equatable添加到Place

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
    }
    //...        
}

并使用删除的地方过滤数组元素

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 }