gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:50:06 26 4
gpt4 key购买 nike

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

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)
]

我找到了一些答案 1 , 2但我不能使用它,因为我的数组不是 Equatable。是否可以在数组的 swift 中使用 filter 删除它?

最佳答案

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

关于arrays - 如何使用过滤器快速删除位置坐标数组中的重复位置坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com