Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] ()

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
}
like image 757
Samkit Jain Avatar asked Dec 16 '15 06:12

Samkit Jain


People also ask

What is the difference between weak self and unowned self?

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.

What does weak self mean?

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.

Should I always use weak self?

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.

What is the difference between self and self in Swift?

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.


1 Answers

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.

like image 155
Martin R Avatar answered Sep 25 '22 08:09

Martin R