在here发布的问题中,用户询问:
作为响应,他得到了以下代码:
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中的这段代码可能会大有帮助。
最佳答案
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)")
或作为功能:
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
}
关于ios - 从用户位置查找数组中最接近的经度和纬度-iOS Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33927405/