gpt4 book ai didi

ios - 在 Swift 中找出 Grand Central Dispatch 的语法

转载 作者:IT王子 更新时间:2023-10-29 05:47:53 24 4
gpt4 key购买 nike

我有以下代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

// Do stuff in the backgroud

dispatch_async(dispatch_get_main_queue()) {

// Do stuff on the UI thread

}
}

但是它不会编译。对 dispatch_async 的内部调用返回以下编译错误:

Cannot invoke 'init' with an argument list of type '(dispatch_queue_t!, () -> () -> $T3)'

我似乎无法弄清楚如何编写它才能像我以前在 Objective C 中那样工作。感谢您的任何想法!

最佳答案

Swift 中的闭包如果只包含一个表达式则可以有隐式返回(参见:Implicit Returns from Single-Expression Closures)。您的内部闭包很可能只有一个表达式来更新 UI。编译器使用该表达式的结果作为闭包的返回值,这使得闭包的签名与 dispatch_async 想要的签名不匹配。由于 dispatch_async 想要一个返回 ()(或 Void)的闭包,解决方法是添加一个显式的 return 在结束时:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

// Do stuff in the backgroud

dispatch_async(dispatch_get_main_queue()) {

// Do stuff on the UI thread

return
}
}

关于ios - 在 Swift 中找出 Grand Central Dispatch 的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com