在这里发表的问题中,用户问道:
我有一个包含经纬度信息的数组。我有两个双精度变量代表我的用户位置。我希望测试我的用户位置与数组中其他位置之间的距离,以找出最近的位置。该怎么做?
我知道如何获取2个位置之间的距离,但是不清楚如何将其应用到位置数组中。
回答者给出了以下代码:
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);
我在一个应用程序中遇到了完全相同的问题,我认为这段代码可能非常适合。但是,我正在使用Swift,而这段代码是Objective-C。
我的唯一问题是:在Swift中应该看起来怎么样?
谢谢任何帮助。我对所有这些都很新,并且在Swift中看到这段代码可能会有所帮助。