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
}
Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.
In Swift, [weak self] prevents closures from causing memory leaks in your application. This is because when you use [weak self], you tell the compiler to create a weak reference to self. In other words, the ARC can release self from memory when necessary.
Using [weak self] is only required within situations in which capturing self strongly would end up causing a retain cycle, for example when self is being captured within a closure that's also ultimately retained by that same object.
The difference is that self is used in types and instances of types to refer to the type that it's in; and Self is used in protocols and extensions where the actual type is not yet known. In even simpler terms, self is used within an existing type; Self is used to refer to a type that Self is not yet in.
You do not pass [weak self] ()
as an argument to a closure.
[weak self]
is a capture list and precedes the() -> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With