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

ard*_*evd 8 swift

所以我有一组自定义对象,它们具有Double纬度和Double经度值.我想基于从特定点到阵列中每个项目的位置的计算距离对数组进行排序.我有一个功能,将根据纬度和经度值计算距离.有没有简单的方法来完成这种排序?

xou*_*ini 22

假设您有一个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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后var places: [Place]可以按如下方式对数组进行排序:

places.sort(by: { $0.distance(to: myLocation) < $1.distance(to: myLocation) })
Run Code Online (Sandbox Code Playgroud)


Gre*_*reg 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)
}
Run Code Online (Sandbox Code Playgroud)