简体   繁体   English

我的 Swift 应用程序完成处理程序似乎不起作用

[英]My Completion Handler for a Swift App Doesn't Seem to Work

I'm using a method found here to convert a street address to coordinate points.我正在使用此处找到的方法将街道地址转换为坐标点。 My completion handler, when successful, should add the coordinate points to a list that I've initialized, but when I go into debug mode, the completion handler is ignored completely causing an Index Out Of Range Error.我的完成处理程序成功后,应该将坐标点添加到我已经初始化的列表中,但是当我进入调试模式时,完成处理程序被完全忽略,导致索引超出范围错误。 I think I'm doing something wrong with my completion handler which can be found below:我想我的完成处理程序有问题,可以在下面找到:

func setUp() {
    for a in addresses {
        print(a)
        getCoordinate(address: a, completionHandler: {coord , error in
            
            if error == nil {
            items.append(Location(coordinate: CLLocationCoordinate2D(latitude: coord.latitude, longitude: coord.longitude), address: a))
                print("resulting coordinate = (\(coord.latitude),\(coord.longitude))")
            
            } else {
                print(error as Any)
            }
            
        })
        
    }
        
}

So to summarize, when I go to debug this problem, the debugger gets to line 4 in the snippet and then skips over the rest of the function.总而言之,当我去调试这个问题时,调试器会到达代码片段中的第 4 行,然后跳过函数的其余部分。 Thanks for any help!谢谢你的帮助!

That is how async code works.这就是异步代码的工作原理。 You make the call, and pass it a completion handler.您进行调用,并将其传递给完成处理程序。 The function call returns immediately.函数调用立即返回。 At some future date, the aysnc function finishes its work, and then it calls your completion handler.在未来的某个日期, aysnc 函数完成其工作,然后调用您的完成处理程序。

Think of it like asking your kid to run to the store to buy some ingredients you need to finish making dinner.把它想象成让你的孩子跑到商店买一些你完成晚餐所需的原料。 You give your kid the list send them on their way, and then go back to cooking the rest of dinner.你把清单发给你的孩子,让他们在路上,然后回去做剩下的晚餐。 When they come back, after an unpredictable delay, they tell you they have the stuff (call your completion handler) and at that point you take the items they gave you (Your completion handler can take parameters from the async function.)当他们回来时,经过不可预知的延迟,他们告诉你他们有东西(调用你的完成处理程序),然后你拿走他们给你的项目(你的完成处理程序可以从异步函数中获取参数。)

If you set a breakpoint inside the completion handler, on the function call, and after the function call, you'll see the debugger first hit the function call, then the after-function-call breakpoint, and then at some future time you'll see it hit the completion handler code's breakpoint.如果您在完成处理程序中、在函数调用中以及在函数调用之后设置断点,您将看到调试器首先命中函数调用,然后是函数调用后断点,然后在以后的某个时间将看到它击中完成处理程序代码的断点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM