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

我有以下代码
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)的闭包,因此修复只是在闭包结束时添加一个显式返回:
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
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...