Swift Direction Request 无法在 if 语句中正确计算

标签 swift if-statement fatal-error optional-values mkdirection

我想计算从用户当前位置到许多不同位置的距离,并将这些计算结果放入计算数组中。所以我可以对这个数组进行排序并找到最近的位置。最后,我想在表格 View 的顶部显示最近的位置,以提高用户体验。但我无法正确地将每个计算附加到“计算数组”中。请参阅我在代码末尾使用 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) 

最佳答案

问题是 directions.request 是一个异步方法,因为它需要调用 Apple 的服务器来计算距离,并且您尝试在请求实际返回之前使用它的值。另请注意,大多数需要网络请求的 MapKit 调用都有速率限制,因此,如果您连续进行 20 次调用,您可能会受到速率限制(即使 Apple 没有发布其确切的速率限制)数字,因此您不知道这种情况何时发生)。

您需要等待所有方向请求完成执行才能使用它们的值。如果数组为空,Array.min() 返回 nil,这里就是这种情况,因此会出现错误。

关于Swift Direction Request 无法在 if 语句中正确计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45448335/

相关文章:

ios - 将 Game over 实现到 swift 游戏中

Swift:连续两次将数据从一种形式传递到另一种形式:第二次拒绝传递

ios - 如何在Core Data中的NSFetchedResultsController中使用缓存

python - 想要从输出中获得最大值并将其应用到方程中

python - 为什么 elif 在 if 语句之前运行? Python

swift - fatal error : Range end index has no valid successor

swift - 在 DateFormatter 中使用 NumberFormatter

PHP fatal error : Call to undefined function test_input() in C:\wamp\www\web\new9. php 第 11 行

error-handling - 如何修复 "fatal error: can' t 索引空缓冲区”

php - Yii 中的 fatal error 处理