所以我有一组自定义对象,它们具有Double纬度和Double经度值。我想基于从特定点到阵列中每个项目的位置的计算距离对数组进行排序。我有一个功能,将根据纬度和经度值计算距离。有没有简单的方法来完成这种排序?
答案 0 :(得分:20)
假设您的对象有一个模型Place
:
class Place {
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var location: CLLocation {
return CLLocation(latitude: self.latitude, longitude: self.longitude)
}
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
}
然后可以对数组var places: [Place]
进行排序:
places.sort(by: { $0.distance(to: myLocation) < $1.distance(to: myLocation) })
答案 1 :(得分:0)
这很容易做到。 计算距离的函数必须采用两个类型的参数,您想要排序并返回Bool,例如:
// I assumed your array stores MyLocation
func mySortFunc(location1: MyLocation, location2: MyLocation) -> Bool {
// do your calculation here and return true or false
}
var array: [MyLocation] = ...
array.sortInPlace { (loc1, loc2) -> Bool in
mySortFunc(loc1, location2: loc1)
}
答案 2 :(得分:0)
解决此问题的另一种方法是在Array上进行扩展,使您可以按位置排序。这种方法的好处是呼叫站点更加整洁并且易于理解。
**注意**-我已将class
更改为struct
。但是,这对于一个类也可以正常工作。
struct Place {
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var location: CLLocation {
return CLLocation(latitude: self.latitude, longitude: self.longitude)
}
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
}
然后我们像这样声明扩展名,其中数组的Element
是Place
:
extension Array where Element == Place {
mutating func sort(by location: CLLocation) {
return sort(by: { $0.distance(to: location) < $1.distance(to: location) })
}
func sorted(by location: CLLocation) -> [Place] {
return sorted(by: { $0.distance(to: location) < $1.distance(to: location) })
}
}
这使我们可以使用以下语法按位置进行排序:
places.sort(by: myLocation)
//变异版本
let newPlaces = places.sorted(by: myLocation)
//非变异版本