简体   繁体   English

弱自我与弱自我的区别()

[英]Difference between weak self vs weak self()

What is the difference between passing [weak self] as an argument to a closure vs passing [weak self] () [weak self]作为一个参数传递给一个闭包与传递[weak self] ()之间有什么区别?

For example : 例如 :

dispatch_async(dispatch_get_main_queue()) { [weak self] in 
     //Some code here
}

v/s V / S

dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
     //Some code here
}

You do not pass [weak self] () as an argument to a closure. 你没有将[weak self] ()作为参数传递给闭包。

  • [weak self] is a capture list and precedes the [weak self]是一个捕获列表 ,位于之前
  • parameter list/return type declaration () -> Void 参数列表/返回类型声明() -> Void

in the closure expression. 在闭包表达式中。

The return type or both parameter list and return type can be omitted if they can be inferred from the context, so all these are valid and fully equivalent: 如果可以从上下文中推断出返回类型或者参数列表和返回类型,则可以省略它们,因此所有这些都是有效且完全等效的:

dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in 
    self?.doSomething()
}

dispatch_async(dispatch_get_main_queue()) { [weak self] () in 
    self?.doSomething()
}

dispatch_async(dispatch_get_main_queue()) { [weak self] in 
    self?.doSomething()
}

The closure takes an empty parameter list () and has a Void return type. 闭包采用空参数list ()并具有Void返回类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM