在dispatch_async中正确引用self

LB.*_*LB. 9 closures ios swift

如何在快速关闭中正确引用自我?

dispatch_async(dispatch_get_main_queue()) {
    self.popViewControllerAnimated(true)
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Cannot convert the expression's type 'Void' to type 'UIViewController!"

随机我试过:

dispatch_async(dispatch_get_main_queue()) { ()
    self.popViewControllerAnimated(true)
}
Run Code Online (Sandbox Code Playgroud)

它起作用了.不确定extra()的作用!有人在乎解释吗?谢谢!

Jac*_*ack 4

这与人们遇到的以下问题是同一个问题:

我在 Swift 中调用此 Objective-C 块/API 调用时做错了什么?

animateWithDuration:animations:completion: 在 Swift 中

总体思路如下:

来自 Swift 书籍:https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Closures.html

Closures 的优化之一是:

单表达式闭包的隐式返回

因此,如果闭包中只有一行,则闭包的返回值会发生变化。在这种情况下,popViewController返回正在弹出的视图控制器。通过添加()到闭包,您只需将其设为 2 行闭包,并且返回值不再是隐式的!