Difference between weak self vs weak self()
Asked Answered
L

1

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
}
Lilah answered 16/12, 2015 at 6:40 Comment(1)
@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?Lilah
E
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.

Exhilarate answered 16/12, 2015 at 7:0 Comment(5)
() = Void. You should actually prefer Void instead of () for clarity, thus this should be Void -> VoidArtificial
@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.Exhilarate
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 preferArtificial
Well, ()->Void is how the Swift compiler imports the C definition of dispatch_block_t. – Do you have references for #2?Exhilarate
Looked it up and apparently you were right. The community prefers ()->Void. From Erica Sadun's blogArtificial

© 2022 - 2024 — McMap. All rights reserved.