我想计算从用户当前位置到许多不同位置的距离,并将这些计算放入计算数组中。所以我可以对这个数组进行排序并找到最近的位置。最后,我想在表格视图的顶部显示最近的位置以供用户体验。但我不能正确地将每个计算附加到“计算数组”中。请查看我在代码末尾使用 print() 获得的输出。我在哪里做错了?感谢您的帮助。
override func viewDidLoad() {
super.viewDidLoad()
visualEffect.isHidden = true
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
Calculate()
}
var closestDistanceIndex:Int = 0
func Calculate() {
// anlık lokasyona en yakın giriş hesaplaması
var calculations:[Double] = []
var distance:Double = 0.0
var i = 1
while i < (giselerGiris.count)
{
print("index \(i)")
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let source1 = MKMapItem( placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(locValue.latitude, locValue.longitude),
addressDictionary: nil))
let destination1 = MKMapItem(placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(girisLatitude[i], girisLongtitude[i]),
addressDictionary: nil))
let directionsRequest = MKDirectionsRequest()
directionsRequest.source = source1
directionsRequest.destination = destination1
directionsRequest.transportType = .automobile
let directions = MKDirections(request: directionsRequest)
directions.calculate { (response, error) -> Void in
print("hata \(String(describing: error))")
distance = (response!.routes.first?.distance)!
print("distance is \(distance)")
calculations.append(distance)
}
print("distance \(i): \(distance)")
i += 1
}
let closestDistance = calculations.min()!
print("closest distance is \(closestDistance)")
closestDistanceIndex = calculations.index(of: closestDistance)!
print("closest distance index is \(closestDistanceIndex)")
}
我得到以下错误
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
在这一行
let closestDistance = calculations.min()!
这是输出
index 1
distance 1: 0.0
index 2
distance 2: 0.0
index 3
distance 3: 0.0
index 4
distance 4: 0.0
index 5
distance 5: 0.0
index 6
distance 6: 0.0
index 7
distance 7: 0.0
index 8
distance 8: 0.0
index 9
distance 9: 0.0
index 10
distance 10: 0.0
index 11
distance 11: 0.0
index 12
distance 12: 0.0
index 13
distance 13: 0.0
index 14
distance 14: 0.0
index 15
distance 15: 0.0
index 16
distance 16: 0.0
index 17
distance 17: 0.0
index 18
distance 18: 0.0
index 19
distance 19: 0.0
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)