In the question answer here, the user asked:
I have an array full of longitude and latitude. I have two double variables with my users location. I would like to check the distance between my user locations against my array to find out which location is closest. How to do it?
This will allow you to get the distance between the two locations, but clouding over to understand how I would check it for an array of locations.
In response, he received the following code:
NSArray *locations = //your array of CLLocation objects CLLocation *currentLocation = //current device Location CLLocation *closestLocation; CLLocationDistance smallestDistance = DBL_MAX; // set the max value for (CLLocation *location in locations) { CLLocationDistance distance = [currentLocation distanceFromLocation:location]; if (distance < smallestDistance) { smallestDistance = distance; closestLocation = location; } } NSLog(@"smallestDistance = %f", smallestDistance);
I have the same problem in the application I'm working on, and I think this piece of code can work just fine. However, I use Swift, and this code is in Objective-C.
My only question is: what should it look like in Swift?
Thanks for any help. I am new to this and see that this piece of code in Swift can be a big foot.
source share