正确引用dispatch_async中的self
我如何恰当地引用自我迅速closures?
dispatch_async(dispatch_get_main_queue()) { self.popViewControllerAnimated(true) }
我得到的错误:
Cannot convert the expression's type 'Void' to type 'UIViewController!"
随机我试过:
dispatch_async(dispatch_get_main_queue()) { () self.popViewControllerAnimated(true) }
它的工作。 不知道多余()做什么! 任何人都在意解释? 谢谢!
这是人们遇到这些问题的同样的问题:
我在Swift中做了什么错误来调用这个Objective-C块/ API调用?
animateWithDuration:animation:完成:在Swift中
这是一般的想法:
从Swift书: https : //developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Closures.html
closures的优化之一是:
来自单expression式闭包的隐式返回
因此,如果在闭包中只有一行,则闭包的返回值会改变。 在这种情况下, popViewController
返回被popup的视图控制器。 通过在闭包中添加()
,你可以使它成为一个2行闭包,返回值不再隐含了!
几天前我回答了类似这样的问题:Swift的“单expression式闭包的隐式返回值”: animateWithDuration:animation:completion:在Swift中
在这种情况下, popViewControllerAnimated
方法返回从堆栈popup的UIViewController:( https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html#//apple_ref/ occ / instm / UINavigationController / popViewControllerAnimated 🙂
即使你没有明确地使用该方法的返回值做任何事情,Swift仍然使用该值(返回的UIViewController)作为闭包的返回值 – 但是,闭包期望返回值为Void。
当你添加额外的parens ()
,你基本上在闭包中添加了另外一行,并且由于它不再是一个“单expression式闭包”,它不再隐含地返回popup的UIViewController。
社区最终会处理一个处理这个问题的约定,因为现在当我碰到它的时候,我一直主张把return ()
加到closures的末尾(因为它清楚地表明了这个意图,(1)短路了'隐式返回“,增加另一个语句,(2)显式返回所期望的)。