2017-10-28 74 views
0

我有一个闭合计算两个点之间的距离和时间,但我需要封闭的外提取值(方向和journeyTimes)的阵列。夫特完成处理程序

我敢肯定完成处理程序是要走的路,但也不太清楚如何实现它。

我的代码:

VAR completionHandlers:[() - >空隙率] = []

@IBAction func calculateItinerary(_ sender: Any) { 

    // start calc 

    for index in 0...coordsOfCollective.count - 2 { 

     let sourceLocation = MKPlacemark(coordinate: coordsOfCollective[index]) 

     let destinationLocation = MKPlacemark(coordinate: coordsOfCollective[index + 1]) 

     let sourceMapItem = MKMapItem(placemark: sourceLocation) 
     let destinationMapItem = MKMapItem(placemark: destinationLocation) 

     let request = MKDirectionsRequest() 
     request.source = sourceMapItem 
     request.destination = destinationMapItem 

     request.transportType = .automobile 
     request.requestsAlternateRoutes = false 


     let directions = MKDirections(request: request) 

     directions.calculate { response, error in 
      if let route = response?.routes.first { 
       print("Distance: \(route.distance/1000) km, ETA: \(route.expectedTravelTime/60) mins") 

      self.distances.append(route.distance/1000) 
      self.journeyTimes.append(route.expectedTravelTime/60) 

       print(self.distances) 
       print(self.journeyTimes) 

       completionHandlers.append(?????) 

      } else { 
       print("Error!") 
      } 

     } 
    } 

print(completionHandlers) 

} 

的directions.calculate具有计算的声明(completionHandler:@escaping MKDirectionsHandler),所以我可以看到它是一个逃避关闭。但我不知道如何从中提取距离和journeyTimes数组。打印功能目前产生的值,但不能从其他地方访问。

任何帮助表示赞赏。谢谢。

回答

1
var completionHandlers: [() -> Void] = [] 

for i in 1...10 { 

    let handler = { 

     print(i) 

    } 

    completionHandlers.append(handler) 

} 

之后,你可以执行处理程序:

completionHandlers[0]() 

,或者使代码更传神:

let handler = completionHandlers[0] 
handler() 

并且要经过所有的处理程序:

completionHandlers.forEach { handler in 
    handler() 
} 

要小心,当您将处理程序存储在数组中时,您对此有很强的参考。由于封闭保持一个强引用您在关闭中提到的一切,它很容易地创建一个参考周期,当您参考self

let handler = { 
    self.myFunction() 
} 

您可以通过一个弱引用自避免retaicnycle:

let handler = { [weak self] in 
    self?.myFunction() 
} 
+0

感谢马塞尔。所以我基本上将我的计算存储为处理程序,然后将其附加到completionHandler数组中? – mathleticolewis

+0

为什么你要处理的闭合以外的计算?你可以确保你没有通过使用'.calculate {[weak self]响应,在' – Marcel

+0

错误中对我自己做出强烈的引用我试图将计算结果传递给另一个视图控制器。所以我认为做这件事的最好方法是制作一系列结果,然后将它们传递给segue。 – mathleticolewis