使用可选的完成处理程序调用自身进行迭代,不会第二次完成

iterating using optional completion handler calling itself, wont complete second time around

我收到这个错误:

Value of optional type '((RestTime) -> ())?' must be unwrapped to a value of type '(RestTime) -> ()'

我从 VC:

调用函数
        let calculateSegmentDirections = CalculateSegmentDirections(locationManager: locationManager)
        calculateSegmentDirections.calculateSegmentDirections(index, time: time, routes: routes, loc: loc) { restTime in
                print("4")

        }




    func calculateSegmentDirections(_ index: Int, time: TimeInterval, routes: [MKRoute], loc: LocationModel, completion: ((_ restTime: RestTime) -> ())?) {
            print("1")
            if let routeResponse = response?.routes {
            print("2")
                    self.calculateSegmentDirections(index+1, time: timeVar, routes: routesVar, loc: restLocation, completion: nil)
                } else {
                    let restTime = RestTime(objectID: restLocation.objectID, time: timeVar, routes: routesVar)
                    print("3")
                    completion(restTime)
                }
    }

完整形式的函数从 VC 调用,然后迭代自身以从 MKdirections 创建一条路线。我的问题是,我可以通过这种方式使用可选的完成处理程序吗?

控制台按预期打印 1、2、1、3,但随后没有调用完成。 4 从未被解雇。 completion = nil,所以当我用 if completion = completion 解包时它不起作用。

此外,completion?(restTime) 也不起作用,将默认值设置为 nil 也不起作用,就像我检查 print(completion) = nil 时一样。

猜测发生了什么: 第一个完成处理程序 "completing the function" 因此第二个不触发吗?我传递了一个 nil 值,而不是 运行 吗?

抱歉,如果这很简单,google 是紫色的,但仍然不确定我做错了什么。

我认为问题出在这里:

// ... 
print("2")
self.calculateSegmentDirections(index+1, time: timeVar, 
         routes: routesVar, loc: restLocation, completion: nil)
// ...

当你递归调用calculateSegmentDirections时,你没有提交完成处理程序而是nil。这是故意的吗?在我看来,这应该是:

// ... 
print("2")
self.calculateSegmentDirections(index+1, time: timeVar, 
         routes: routesVar, loc: restLocation, completion: completion)
// ...