7

What is the difference between passing [weak self] as an argument to a closure vs passing [weak self] ()

For example :

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

v/s

dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
     //Some code here
}
Samkit Jain
  • 2,523
  • 16
  • 33
  • @MartinR updated code. Actually in some implementations I see [weak self] being used without round brackets and in some I see it being used as [weak self](). What exactly is the difference between these two? – Samkit Jain Dec 16 '15 at 06:57

1 Answers1

9

You do not pass [weak self] () as an argument to a closure.

  • [weak self] is a capture list and precedes the
  • parameter list/return type declaration () -> 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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • () = Void. You should actually prefer Void instead of () for clarity, thus this should be Void -> Void – Yariv Nissim Dec 16 '15 at 21:43
  • @yar1vn: That may be a matter of personal taste. I prefer `()` for an empty/void parameter list, and `Void` as return type. That is also what Apple does in the `dispatch_block_t` definition. – Martin R Dec 16 '15 at 21:54
  • 1. dispatch_block_t is not a Swift func. 2. The Swift community is creating the standard and it prefers Void. 3. But you're right, since they both work you can choose whichever you prefer – Yariv Nissim Dec 16 '15 at 21:57
  • Well, `()->Void` is how the Swift compiler imports the C definition of dispatch_block_t. – Do you have references for #2? – Martin R Dec 16 '15 at 21:59
  • Looked it up and apparently you were right. The community prefers ()->Void. From Erica Sadun's blog – Yariv Nissim Dec 17 '15 at 22:52