在Swift中按计算的距离对数组进行排序

编程入门 行业动态 更新时间:2024-10-14 12:27:26
本文介绍了在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中按计算的距离对数组进行排序

本文发布于:2023-10-18 15:01:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   距离   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!