[weak self] when the closure may run after the object is deallocated, or [unowned self] only when you can guarantee the object will still exist whenever the closure accesses it. A strong capture is appropriate when keeping the object alive is intentional and no permanent cycle results.Why this happens
Swift uses Automatic Reference Counting (ARC) to manage the lifetime of class instances. A closure normally captures a referenced class instance strongly. That keeps the instance alive for as long as the closure needs its captured reference.
A problem occurs when the instance also retains the closure, directly or through other objects. Neither side can be released because each keeps the other alive. For example, if a TempNotifier stores an onChange closure and that closure strongly captures the notifier, the two form a retain cycle.
This does not mean every closure needs [unowned self]. A strong capture can be useful when an operation needs the object to remain alive until its work finishes. The right choice depends on who retains the closure and whether it can run after the captured object has been deallocated.
How to fix it
1. Use [weak self] when the closure may outlive the object
A weak capture breaks the closure’s strong reference to the object. It also makes self optional inside the closure, so you can skip the work if the object has already gone away.
Here is a notifier that stores its own callback:
final class TempNotifier {
var currentTemp = 72
var onChange: (Int) -> Void = { _ in }
init() {
onChange = { [weak self] temp in
guard let self = self else { return }
self.currentTemp = temp
}
}
}
The notifier strongly retains onChange, but the closure does not strongly retain the notifier. If another part of the program saves the callback and calls it after the notifier is deallocated, the guard returns without updating anything.
For a single optional operation, optional chaining is also enough:
onChange = { [weak self] temp in
self?.currentTemp = temp
}
Choose this behavior when the callback is no longer useful without its owner. For example, a screen may not need to update its interface after the screen’s controller has been deallocated. If the work must still happen regardless, moving it to an object with a more appropriate lifetime may be a better design than silently skipping it.
When you use guard let self = self, the unwrapped reference is strong for the rest of that invocation. This lets the closure safely use the object while it performs that work; it does not change the stored closure’s weak capture.
2. Use [unowned self] only with a lifetime guarantee
An unowned capture also avoids a strong reference cycle, but it does not become an optional. Accessing it after the object has been deallocated causes a runtime crash.
In the notifier example, you can use unowned if you can guarantee that the closure will never access the notifier after it has been deallocated:
final class TempNotifier {
var currentTemp = 72
var onChange: (Int) -> Void = { _ in }
init() {
onChange = { [unowned self] temp in
self.currentTemp = temp
}
}
}
That guarantee requires more than noticing that the notifier stores the closure. A closure can be copied and stored elsewhere:
var notifier: TempNotifier? = TempNotifier()
let savedCallback = notifier!.onChange
notifier = nil
// Calling savedCallback now would access a deallocated notifier.
With the unowned implementation, calling savedCallback after the final line would crash. With the weak implementation, it would return without doing anything. If the callback can escape to a longer-lived object and the lifetime guarantee is unclear, prefer weak capture and handle the missing object explicitly.
3. Keep a strong capture when the work needs the object
A strong capture is not automatically a leak. It is a problem when it participates in a cycle that is not broken. If an independently owned, finite operation retains a closure, keeping an object alive until the callback finishes can be intentional.
For example, a request handler might need to record the result even if the code that started the request no longer holds a reference to it:
import Foundation
final class RequestLogger {
func startRequest(at url: URL) {
URLSession.shared.dataTask(with: url) { _, _, error in
self.recordResult(error: error)
}.resume()
}
private func recordResult(error: Error?) {
if let error = error {
print("Request failed: \(error)")
} else {
print("Request finished")
}
}
}
Here the closure deliberately captures the logger strongly. The example does not store the task in the logger, so the code shown does not create a direct logger-to-closure cycle. The logger can remain alive while the operation retains its callback; that may be longer than the caller expects. A completion callback also does not imply that a response had a successful HTTP status.
Do not apply strong capture to every network callback by default. If the callback only updates a screen that may disappear, weak capture may better match the desired behavior. Also inspect any stored task, session, or intermediary object for an ownership path back to the closure.
4. Break a stored callback cycle when the callback is no longer needed
Sometimes a strong capture is intentional while a callback is active, but the owning object should release it afterward. In that design, give the callback an explicit end point. For an optional closure property, that can mean assigning nil when the subscription or operation ends:
final class TemperatureObserver {
var onStop: (() -> Void)?
func stop() {
onStop = nil
}
}
This only works if stop() is actually called and the relevant strong ownership path is released. If the object is already unreachable except through a cycle, waiting for its deinit to clear the callback will not resolve that cycle. Use a weak capture instead when there is no reliable cleanup point.
Weak interface outlets do not change this analysis. If a closure accesses an outlet through self, it captures the controller according to the closure’s capture rules. The outlet being weak does not make the closure’s reference to the controller weak.
How to prevent it
- Trace ownership from the object to the closure and back, including any intermediate objects.
- Use
[weak self]when a callback can reasonably run after its owner is gone, and decide what should happen in that case. - Use
[unowned self]only when every access is guaranteed to occur while the object is alive. - Keep strong captures when retaining the object is intentional, but check how and when the callback is released.
- Define a cleanup point for stored callbacks and test whether the owning object is deallocated when expected.
FAQ
Should I always use [unowned self] in Swift closures?
No. It can crash if the closure accesses self after the object has been deallocated. Use it only when you can prove that cannot happen; otherwise consider weak or intentional strong capture.
Does [weak self] guarantee there is no memory leak?
No. It removes that particular strong reference from the closure to self, but other references can still form cycles. Review the full ownership chain, including objects stored by the closure and its owner.
Does a weak IBOutlet prevent a closure retain cycle?
No. A weak outlet controls the controller’s reference to the outlet object. A closure that accesses the outlet through self can still strongly capture the controller unless its capture list says otherwise.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.