In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide
The speaker said in that case, if we don't use [unowned self]
there, it will be a memory leak. Does it mean we should always use [unowned self]
inside closure?
On line 64 of ViewController.swift of the Swift Weather app, I don't use [unowned self]
. But I update the UI by using some @IBOutlet
s like self.temperature
and self.loadingIndicator
. It may be OK because all @IBOutlet
s I defined are weak
. But for safety, should we always use [unowned self]
?
class TempNotifier {
var onChange: (Int) -> Void = {_ in }
var currentTemp = 72
init() {
onChange = { [unowned self] temp in
self.currentTemp = temp
}
}
}
There are some great answers here. But recent changes to how Swift implements weak references should change everyone's weak self vs. unowned self usage decisions. Previously, if you needed the best performance using unowned self was superior to weak self, as long as you could be certain that self would never be nil, because accessing unowned self is much faster than accessing weak self.
But Mike Ash has documented how Swift has updated the implementation of weak vars to use side-tables and how this substantially improves weak self performance.
https://mikeash.com/pyblog/friday-qa-2017-09-22-swift-4-weak-references.html
Now that there isn't a significant performance penalty to weak self, I believe we should default to using it going forward. The benefit of weak self is that it's an optional, which makes it far easier to write more correct code, it's basically the reason Swift is such a great language. You may think you know which situations are safe for the use of unowned self, but my experience reviewing lots of other developers code is, most don't. I've fixed lots of crashes where unowned self was deallocated, usually in situations where a background thread completes after a controller is deallocated.
Bugs and crashes are the most time-consuming, painful and expensive parts of programming. Do your best to write correct code and avoid them. I recommend making it a rule to never force unwrap optionals and never use unowned self instead of weak self. You won't lose anything missing the times force unwrapping and unowned self actually are safe. But you'll gain a lot from eliminating hard to find and debug crashes and bugs.
According to Apple-doc
Example -
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html
Update 11/2016
I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.
Original answer
The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.
The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.
Scenarios
You can have two possible scenarios:
The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the
[unowned self]
used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the
[weak delegate]
you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.Actual Usage
So, which will/should you actually use most of the times?
Quoting Joe Groff from twitter:
You'll find more about unowned
*
inner workings here.*
Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):
weak
, because they are long lived. The view controller could close before the request completes soself
no longer points to a valid object when the closure is called.If you have closure that handles an event on a button. This can be
unowned
because as soon as the view controller goes away, the button and any other items it may be referencing fromself
goes away at the same time. The closure block will also go away at the same time.Here is brilliant quotes from Apple Developer Forums described delicious details:
unowned
vsunowned(safe)
vsunowned(unsafe)
unowned
vsweak
Update: In modern Swift
weak
internally uses the same mechanism asunowned
does. So this comparison is incorrect because it compares Objective-Cweak
with Swiftunonwed
.Reasons
Excited, huh?