As a Swift team lead, would you mandate [weak self] in every escaping closure, ban it, or decide case by case, and how would you make the rule stick?
answer
- who stores the closure
- must the work finish
- capture dependencies, not self
- unowned needs proven lifetime
- non-escaping needs nothing
basics
~20 sDecide by case under a written default: weak self when the work is pointless once the owner is gone or the owner holds the closure's storer; capture only the needed dependencies when work must finish; unowned only for structurally guaranteed lifetimes.
solid answer
~50 sNeither blanket rule survives contact with real code. "Always `[weak self]`" adds optional handling everywhere, silently drops work that had to finish (a photo import abandoned because the screen closed), and once `guard let self` succeeds it still keeps `self` alive while the rest of the body uses it. "Never" leaves stored callbacks holding closed screens alive, or in cycles when the screen owns what stores them. I would write a default with three questions: does the closure escape at all (non-escaping closures such as `map(_:)` never need it); is the work only for this object's UI (then `[weak self]` and bail); must it finish regardless (then capture the dependencies it needs, like `[store]`, strongly and leave `self` out). `[unowned self]` only when the closure is stored by `self` and cannot outlive it, since a mistake is a crash. A review checklist and a lint flag on `unowned self` enforce it.
code
swift · 34 linesfinal class PhotoStore {
func save(_ image: String) { print("saved", image) }
}
final class ImageDownloader {
func download(_ url: String, completion: @escaping (String) -> Void) {
completion("bytes of \(url)")
}
}
final class GalleryScreen {
let downloader = ImageDownloader()
let store = PhotoStore()
var shown: [String] = []
func showThumbnail() {
// Pointless once the screen is gone: capture self weakly and bail out.
downloader.download("thumb.png") { [weak self] image in
guard let self else { return }
shown.append(image)
}
}
func importOriginal() {
// Must finish even if the screen closes: capture only the store, strongly.
downloader.download("original.png") { [store] image in
store.save(image)
}
}
}
let screen = GalleryScreen()
screen.showThumbnail()
screen.importOriginal()
print(screen.shown)go deeper
Know that [weak self] is common in escaping completion handlers and that non-escaping closures such as map never need it.
Explain how weak and unowned differ when the owner disappears, and why a strong capture in a stored callback can keep a closed screen alive.
Choose the capture per closure: weak for UI-only work, captured dependencies for must-finish work, unowned only with proven lifetime, and justify each in review.
Own the team default and its enforcement: a written decision table, lint flags for unowned self, deallocation tests, and a revisit when targets move to Swift 6 language mode.
## Why each blanket rule fails Teams usually start with one of two slogans. Both break on ordinary code. **"Always write `[weak self]` in escaping closures."** - It turns every handler into optional handling, and the `guard let self else { return }` line becomes a reflex nobody reads. - It **drops work silently**. If a gallery screen starts saving an imported photo and the user leaves, a weak capture returns early and the photo is never saved. - It does not do what people assume once unwrapped: after `guard let self` succeeds, the local strong reference keeps the object alive while the rest of that run uses it. - It hides design problems — a closure that only needs a store or a service should capture that, not the whole screen. **"Never use `[weak self]`; review for cycles instead."** - Long-lived owners such as downloaders, observers and caches store closures. A strong `self` keeps a closed screen alive until the storer lets go — or indefinitely when the screen owns that storer, a reference cycle (covered with ARC and reference cycles). - Reviewers miss these, because nothing fails until memory grows or a stale screen reacts to an event. ## The questions that decide each closure 1. **Does it escape?** A closure passed to a non-escaping parameter — `map(_:)`, `filter(_:)`, `sorted(by:)`, most synchronous helpers — cannot outlive the call. No capture strength matters there. 2. **Who stores it, and does `self` own that storer?** If yes, a strong capture forms a cycle; capture `self` weakly or capture narrower dependencies. 3. **Is the work only meaningful for `self`?** Updating this screen's UI after a download: `[weak self]` and return early when it is gone. 4. **Must the work finish regardless?** Saving, uploading, flushing a log: capture the **dependencies** it needs (`[store]`, `[uploader]`) strongly and leave `self` out, so the owner can go away while the work completes. 5. **Is the closure's lifetime provably bounded by `self`?** Only then consider `[unowned self]`. ## Decision table | Closure | Recommended capture | Why | |---|---|---| | Non-escaping (`map(_:)`, `forEach(_:)`) | none | cannot outlive the call | | UI update after a network response | `[weak self]` + `guard let self` | pointless once the screen is gone | | Must-finish side effect (save, upload) | `[store]` or similar dependency | work completes; screen is not retained | | Closure stored in a property of `self`, called only by `self` | `[unowned self]` or `[weak self]` | lifetimes are tied; unowned needs that proof | | One-shot handler the storer releases after calling | strong is acceptable | delays deallocation until the call, no lasting cycle | ## Where unowned belongs The Swift book frames `unowned` for a closure and instance that "will always refer to each other, and will always be deallocated at the same time", and `weak` for a reference that may become `nil`. In practice that is a closure stored in a property of the same object (the book's `lazy var asHTML` example). The cost of being wrong is a crash — `Fatal error: Attempted to read an unowned reference but object … was already destroyed` — so a team rule should require a one-line justification for every `unowned self`. ## Language details the rule must account for - An escaping closure in a class must already write `self.` or put `self` in a capture list before using members, so every strong capture of `self` is visible in review. - Since Swift 5.8, members can be used implicitly after `guard let self`, which keeps weak-capture bodies short. - In **Swift 6 language mode**, a `[weak self]` in a non-escaping closure must also be unwrapped before implicit `self` is allowed; Swift 5 mode on the 6.4 compiler only warns. One more reason the rule should say "not in non-escaping closures". - Closures handed to concurrency APIs carry their own isolation and sending rules, covered with Sendable and data-race safety; the capture-strength questions above still apply to them. ## Making the rule stick - Write the five questions into the code-review checklist, with the decision table. - Add a lint rule that flags `unowned self` (and optionally strong `self` in stored closures) for an explicit justification comment. - Add deallocation checks for screens in tests, so a regression shows up as a failing test rather than a memory graph — the mechanics belong with ARC and reference cycles. - Revisit the rule when the codebase moves to Swift 6 language mode, because the non-escaping change produces new diagnostics.
- In Swift, why can a blanket [weak self] rule lose user data?A must-finish task, such as saving an imported photo, returns early from `guard let self else { return }` when the user leaves the screen. Capturing only the dependency, `[store]`, lets the save complete without keeping the screen alive.
- When would you accept [unowned self] in a Swift code review?When the closure is stored by `self` and only ever called through `self`, so it cannot run after `self` is gone, and the author states that in a comment. Anywhere a third party stores the closure, such as a downloader or notification observer, require `weak` instead, because a wrong assumption is a crash.
- In Swift, does a strong self in a one-shot completion handler always leak?No. If the downloader releases the handler after calling it and the screen does not own the downloader, the strong capture only delays deallocation until the call. It becomes a lasting leak when the screen owns what stores the handler, forming a cycle.
- Adding [weak self] to every escaping closure is free and always safe.
- A strong self in a one-shot completion handler always leaks memory.
- [unowned self] is the safe, faster default for screen controllers.
- Non-escaping closures like map need [weak self] as well.
- Code review alone reliably catches every capture cycle.
Assumes Swift 6.4: implicit self after guard let self dates from Swift 5.8, and Swift 6 language mode extends the unwrap-first rule to weak self in non-escaping closures.