Sorting an array by calculated distance in Swift

So, I have an array of custom objects that have the meaning of Double latitude and Double longitude. I would like to sort the array based on the calculated distance from a specific point to the location for each element of the array. I have a function that will calculate the distance based on the latitude and longitude values. Is there an easy way to do this sorting?

+4
source share
2 answers

Assuming you have a model Placefor 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)
    }
}

Then the array var places: [Place]can be sorted as such:

places.sort(by: { $0.distance(to: myLocation) < $1.distance(to: myLocation) })
+13
source

. , , , , 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)
}
0

Source: https://habr.com/ru/post/1627273/


All Articles