如何使用过滤器删除swift中位置坐标数组中的重复位置坐标?

时间:2018-05-25 15:10:55

标签: arrays swift

我有一个像这样的位置坐标数组

let coodinatesArray: [CLLocationCoordinate2D] = [
    CLLocationCoordinate2DMake(-37.986866915266461, 145.0646907496548),
    CLLocationCoordinate2DMake(-30.082868871929833, 132.65902204771416),
    CLLocationCoordinate2DMake(-21.493671405743246, 120.25335334577362),
    CLLocationCoordinate2DMake(-20.311181400000002, 118.58011809999996),
    CLLocationCoordinate2DMake(-20.311183981008153, 118.58011757850542),
    CLLocationCoordinate2DMake(-8.3154534852154622, 119.32445770062185),
    CLLocationCoordinate2DMake(4.0574731310941274, 120.06879782273836),
    CLLocationCoordinate2DMake(16.244430153007979, 120.68908125783528), 
    CLLocationCoordinate2DMake(27.722556142642798, 121.4334213799517),
    CLLocationCoordinate2DMake(37.513067999999976, 122.12041999999997)
]

我找到了一些答案12但我无法使用它,因为我的数组不是Equatable。是否可以使用swift for array中的filter删除它?

1 个答案:

答案 0 :(得分:5)

您可以为CLLocationCoordinate2D创建一个扩展名,使其符合Hashable

extension CLLocationCoordinate2D: Hashable {
    public var hashValue: Int {
        return Int(latitude * 1000)
    }

    static public func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
        // Due to the precision here you may wish to use alternate comparisons
        // The following compares to less than 1/100th of a second
        // return abs(rhs.latitude - lhs.latitude) < 0.000001 && abs(rhs.longitude - lhs.longitude) < 0.000001
        return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
    }
}

然后,您可以使用Set获得唯一的位置:

let coodinatesArray: [CLLocationCoordinate2D] = ... // your array
let uniqueLocations = Array(Set(coodinatesArray))

如果您需要保留原始订单,可以将最后一行替换为:

let uniqueLocations = NSOrderedSet(array: coodinatesArray).array as! [CLLocationCoordinate2D]