在dispatch_async中正确引用self [英] Properly referencing self in dispatch_async
问题描述
如何在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:
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屋!