在dispatch_async中正确引用self [英] Properly referencing self in dispatch_async

查看:637
本文介绍了在dispatch_async中正确引用self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在swift闭包中正确引用self?

How do I properly reference self in a swift closure?

dispatch_async(dispatch_get_main_queue()) {
    self.popViewControllerAnimated(true)
}

我得到错误:

无法将表达式类型Void转换为类型UIViewController!

随机我尝试:

dispatch_async(dispatch_get_main_queue()) { ()
    self.popViewControllerAnimated(true)
}

并且它工作不知道extra()什么!感谢!

and it worked. Not sure what the extra () does! Anyone care to explain? Thanks!

推荐答案

这是与人们遇到的问题相同的问题:

This is the same issue as people have run in with these questions:

我在Swift中调用这个Objective-C块/ API调用时出错了什么?

animateWithDuration:animations :completion:in Swift

这里是一个大致的想法:

Here is the general idea:

从Swift的书: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Closures.html

Closures的优化之一是:

One of the optimizations of Closures is:


单表达式闭包的隐式返回


Implicit returns from single-expression closures

因此,如果你的闭包中只有一行,你的闭包的返回值就会改变。在这种情况下, popViewController 返回被弹出的视图控制器。通过在闭包中添加(),你只是使它成为一个2行闭包,返回值不再隐含了!

Thus, if you just have one line in your closure, your closure's return value changes. In this case, popViewController returns the view controller being popped. By adding () to the closure, you just made it a 2-line closure and the return value isn't implicit anymore!

这篇关于在dispatch_async中正确引用self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆