Jason Fel Jason Fel - 3 months ago 27
iOS Question

How can I sort an array of Business objects by distance from user?

I have the following array which is loaded up with businesses:

var businessesArray = [Business]()

Now each Business has a latitude and longitude attribute:

private var _latitude: Double
private var _longitude: Double

What is the most efficient way (using swift) to sort businessesArray by putting business closest to the user at the start and farthest from the user at the end (sorted from nearest to farthest)? Assume I already have the user's current location in these variables:

var currentUserLatitude: Double
var currentUserLongitude: Double


Given this struct (you can also user a class)

struct Business {
    let latitude: Double
    let longitude: Double

    var location: CLLocation {
        return CLLocation(latitude: latitude, longitude: longitude)

The user location

var currentUserLatitude: Double = ...
var currentUserLongitude: Double = ...
let userLocaton = CLLocation(
    latitude: currentUserLatitude,
    longitude: currentUserLongitude

And a list of places

let places: [Business] = ...

This is how you sort them

let sortedPlaces = places.sort { (left, right) -> Bool in
    userLocaton.distanceFromLocation(left.location) < userLocaton.distanceFromLocation(right.location)

How does it work?

The sort method accepts a closure.

Inside this closure you must specify the sorting logic. More specifically, given 2 Business values left and right, if left should be placed before right in the final sorting then the closure returns true. Otherwise false.