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
    }
}

以上是来客网为你收集整理的ios – 在Swift中找出Grand Central Dispatch的语法全部内容,希望文章能够帮你解决ios – 在Swift中找出Grand Central Dispatch的语法所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。