In the question posted here, the user asked:
I have an array full of longitudes and latitudes. I have two double variables with my users location. I\'d like
var closestLocation: CLLocation?
var smallestDistance: CLLocationDistance?
for location in locations {
let distance = currentLocation.distanceFromLocation(location)
if smallestDistance == nil || distance < smallestDistance {
closestLocation = location
smallestDistance = distance
}
}
print("smallestDistance = \(smallestDistance)")
or as a function:
func locationInLocations(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? {
if locations.count == 0 {
return nil
}
var closestLocation: CLLocation?
var smallestDistance: CLLocationDistance?
for location in locations {
let distance = location.distanceFromLocation(location)
if smallestDistance == nil || distance < smallestDistance {
closestLocation = location
smallestDistance = distance
}
}
print("closestLocation: \(closestLocation), distance: \(smallestDistance)")
return closestLocation
}