【问题标题】:How can I remove duplicate location coordinates in an Array of location coordinates in swift using filter?如何使用过滤器快速删除位置坐标数组中的重复位置坐标?
【发布时间】:2018-05-26 00:06:09
【问题描述】:

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

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。是否可以在数组中使用 filter 快速删除它?

【问题讨论】:

  • 此列表中的所有位置均不重复。您希望它们有多接近才被视为“重复”? (双精度比 GPS 实际提供的精度高得多。)只是将 CLLocationCoordinate2D 设置为 Equatable 掩盖了这一事实,使许多“相等”的坐标看起来不同。
  • 使用filter的要求太严格了。

标签: arrays swift


【解决方案1】:

您可以为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]

【讨论】:

  • 我试过了,它会删除重复值,但这会改变位置的顺序。可以在这个数组中使用filter 吗?或任何其他不改变数组中位置顺序的解决方案?
  • 别想在位置的组件之间使用==
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多