我想要检索的阵列MKRoute
,它包含多个路由所有的起始在同一地点,但是每一个具有不同的目的地。
的问题是,我已经能够拿出来做到这一点的唯一方法是通过一个递归函数,但我无法找到如何使用递归函数与完成块东西。由于路由的加载是异步完成的,因此需要完成块。
我如何才能获得以下功能,但要包含完成功能块? “添加到退货”功能?
func factorial(of num: Int) -> Int {
if num == 1 {
return 1
} else {
return num * factorial(of:num - 1)
}
}
这是我的功能代码
func getDirections(originCoordinate: CLLocationCoordinate2D, destinationCoordinates: [CLLocationCoordinate2D], completion: @escaping(_ routes:[MKRoute]?, _ error: Error?) -> Void) {
// Origin is the same for each route, what changes is the destination
// A singular origin coordinate with an array of destination coordinates is passed in
// The function would in theory be recursive, returning each route from the origin to each of the destinations.
// Leave function if no more destination coordinates are passed
if destinationCoordinates.count == 0 {return}
// Origin
let originPlacemark = MKPlacemark(coordinate: originCoordinate)
let originItem = MKMapItem(placemark: originPlacemark)
// Destination is made from the first element of the passed in destinationCoordinates array.
let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinates.first!)
let destinationItem = MKMapItem(placemark: destinationPlacemark)
// Direction Request setup
let directionRequest = MKDirections.Request()
directionRequest.source = originItem
directionRequest.transportType = .automobile
directionRequest.destination = destinationItem
let directions = MKDirections(request: directionRequest)
// Calculating directions
// Heart of function
directions.calculate { (response, err) in
// Checking if a response is returned
guard let response = response else {
completion(nil, err)
return
}
// Response is returned
let route = response.routes[0]
let tail = Array.dropFirst(destinationCoordinates)
// Recursive part that I'm not sure how to properly implement
completion([route].append(getDirections(originCoordinate, tail)), nil)
}
// If no response is retrieved, our guard let statement sends us here
}
答案 0 :(得分:2)
对于具有完成处理程序的函数,在递归调用中,您需要为该调用提供一个闭包,然后在该闭包中调用完成处理程序。
以下是您如何使用factorial
进行的操作:
func factorial(of num: Int, completion: (Int) -> ()) {
if num == 1 {
completion(1)
} else {
factorial(of: num - 1) { partial in
completion(num * partial)
}
}
}
factorial(of: 8) { result in
print(result)
}
40320