【问题标题】:Properly referencing self in dispatch_async在 dispatch_async 中正确引用 self
【发布时间】:2014-06-22 01:03:29
【问题描述】:

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

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

它奏效了。不知道额外的 () 做什么!有人愿意解释吗?谢谢!

【问题讨论】:

  • 如果答案正确,请接受,如果超出您的预期,请点赞。

标签: ios closures swift


【解决方案1】:

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

What am I doing wrong in Swift for calling this Objective-C block/API call?

animateWithDuration:animations:completion: in Swift

大致思路如下:

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

闭包的优化之一是:

单表达式闭包的隐式返回

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

【讨论】:

  • 我不确定这是否算作重复问题,因为他们有同样的问题。如果是,请举报!
【解决方案2】:

几天前我针对一个相关问题回答了类似的问题:Swift 的“单表达式闭包的隐式返回值”:animateWithDuration:animations:completion: in Swift

在这种情况下,popViewControllerAnimated 方法返回从堆栈中弹出的 UIViewController:(https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html#//apple_ref/occ/instm/UINavigationController/popViewControllerAnimated:)

即使你没有显式地对该方法的返回值做任何事情,Swift 还是使用该值(返回的 UIViewController)作为闭包的返回值——然而,闭包期望返回值 Void。

当您添加额外的括号 () 时,实际上您在闭包中添加了另一行,并且由于它不再是“单表达式闭包”,因此它不再隐式返回弹出的 UIViewController。

社区最终会达成一个处理这个问题的约定,现在当我遇到它时,我一直主张在关闭的末尾添加return ()(因为它清楚地说明了意图,(1)短通过添加另一个语句来循环“隐式返回”,以及 (2) 显式返回预期的内容)。

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 2018-08-06
    • 2018-05-21
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多