本文介绍了在Swift中按计算的距离对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一组自定义对象,它们具有双纬度和双经度值.我想根据从特定点到数组中每个项目的位置的计算距离对数组进行排序.我有一个函数可以根据纬度和经度值计算距离.有没有一种简单的方法来完成这种排序?
So I have an array of custom objects which have a Double latitude and Double longitude value. I would like to sort the array based on the calculated distance from a specific point to the location for each item in the array. I have a function that will calculate the distance based on the latitude and longitude values. Is there an easy way to accomplish this sorting?
推荐答案假设您有一个模型 Place 用于您的对象:
Assuming you have a model Place for your objects:
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] 可以这样排序:
Then an array var places: [Place] can be sorted as such:
places.sort(by: { $0.distance(to: myLocation) < $1.distance(to: myLocation) })更多推荐
在Swift中按计算的距离对数组进行排序
发布评论