In Swift, what do [weak self] and [unowned self] do in a download's completion handler when the screen closes before it finishes?
answer
- optional versus non-optional capture
- nil after deallocation
- guard let self
- reading a destroyed object
- a fatal error, not nil
basics
~20 s[weak self] captures an optional reference that becomes nil once the screen is deallocated, so the handler unwraps it and returns early. [unowned self] captures a non-optional reference assumed to be alive; reading it after deallocation traps.
solid answer
~50 sWithout a capture list, a handler that uses `self` holds it strongly, so the downloader keeps the closed screen alive until it releases the handler, and indefinitely if the screen itself owns what stores the handler. `[weak self]` makes `self` a `GalleryScreen?` inside the closure; it turns `nil` once the screen is deallocated, and the usual shape is `guard let self else { return }`, after which (since Swift 5.8) members can be used without writing `self.`. `[unowned self]` keeps `self` non-optional and does not keep it alive; if the screen is gone when the handler runs, the read stops the program with `Fatal error: Attempted to read an unowned reference but object … was already destroyed`. For work a user can walk away from, `weak` is the safe choice; `unowned` fits only when the closure can never outlive the object.
code
swift · 29 linesfinal class ImageDownloader {
private var pending: [(String) -> Void] = []
func download(_ url: String, completion: @escaping (String) -> Void) {
pending.append(completion) // runs later, after download returns
}
func finishAll() { pending.forEach { $0("image-bytes") }; pending.removeAll() }
}
final class GalleryScreen {
var shown: [String] = []
func loadWeak(using downloader: ImageDownloader) {
downloader.download("cat.png") { [weak self] image in
guard let self else { print("screen closed, image dropped"); return }
shown.append(image) // implicit self after unwrapping
}
}
func loadUnowned(using downloader: ImageDownloader) {
downloader.download("dog.png") { [unowned self] image in
shown.append(image) // traps if the screen is gone
}
}
}
let downloader = ImageDownloader()
var screen: GalleryScreen? = GalleryScreen()
screen?.loadWeak(using: downloader)
screen?.loadUnowned(using: downloader)
screen = nil // the user closes the screen first
downloader.finishAll() // weak: dropped; unowned: Fatal errorgo deeper
Recall that weak makes self optional and nil after deallocation, while unowned stays non-optional and crashes if the object is gone.
Walk through the downloader scenario: what the strong default does to the screen's lifetime, how guard let self reads, and why unowned traps instead of returning nil.
Explain when unowned is provably safe, why a strong local after guard let self keeps the object for that run, and how Swift 6 mode changed weak self in non-escaping closures.
Weigh the crash risk of unowned against the optional handling of weak across a codebase, and prefer capturing narrow dependencies over capturing whole screens.
## What the handler captures by default A completion handler that mentions `self` (or uses a property inside a `[self]` capture) stores a **strong reference** to the screen. As long as the downloader holds the handler, the screen cannot be deallocated. For a one-shot handler that the downloader drops after calling, that only **delays** deallocation; if the screen owns the downloader that holds the handler, the two keep each other alive — a reference cycle, covered with ARC and reference cycles. The capture list is how Swift lets you choose a different strength. ## [weak self]: an optional that can turn nil Writing `{ [weak self] image in … }` captures a **weak** reference: - inside the closure `self` has type `GalleryScreen?`, not `GalleryScreen`; - the reference does **not** keep the screen alive; - when the screen is deallocated, the reference automatically becomes `nil`; - `weak` works only on class instances (and class-bound protocol types), never on structs or enums. Two common shapes follow: 1. `self?.shown.append(image)` — optional chaining; each use re-checks for `nil`. 2. `guard let self else { return }` — unwrap once at the top, then use a strong local `self` for the rest of the body. The `guard let self` form has a history worth knowing. Rebinding `self` with `guard let self = self` became legal in **Swift 4.2** (SE-0079), the shorthand `guard let self` arrived with Swift 5.7's `if let x` shorthand (SE-0345), and since **Swift 5.8** (SE-0365) members may be used **implicitly**, as `shown.append(image)`, once `self` is unwrapped. Before unwrapping, an escaping closure still needs explicit `self?.`. In **Swift 6 language mode** the same rule also covers non-escaping closures: `[weak self]` in a `map(_:)` closure must be unwrapped before implicit `self` is allowed. The Swift 6.4 compiler warns about it in Swift 5 mode ("this is an error in the Swift 6 language mode") and rejects it in Swift 6 mode with `explicit use of 'self' is required when 'self' is optional, to make control flow explicit`. ## [unowned self]: non-optional, assumed alive `{ [unowned self] image in … }` captures an **unowned** reference: - `self` stays non-optional — no unwrapping, no `guard`; - the reference does not keep the screen alive either; - it is **not** set to `nil`. Reading it after the instance has gone is a runtime error. The 6.4 runtime prints `Fatal error: Attempted to read an unowned reference but object 0x… was already destroyed`. Plain `unowned` is the checked form, also spelled `unowned(safe)`. `unowned(unsafe)` drops even that check: a read after deallocation touches the memory where the object used to be, which is an unsafe operation rather than a guaranteed trap. ## Side by side | Capture | Type inside closure | Keeps screen alive? | Screen gone when handler runs | |---|---|---|---| | none (strong) | `GalleryScreen` | yes | cannot happen: the handler kept it alive | | `[weak self]` | `GalleryScreen?` | no | `self` is `nil`; the guard returns | | `[unowned self]` | `GalleryScreen` | no | fatal error on first read | | `[unowned(unsafe) self]` | `GalleryScreen` | no | unsafe memory access, no check | ## Choosing for a download a user can abandon The book's guidance is that `unowned` suits a closure and an instance that "will always refer to each other, and will always be deallocated at the same time", and `weak` suits a reference that "may become `nil` at some point in the future". A network callback is the second case: the user can close the screen at any moment, so `[weak self]` with `guard let self` is the correct default there. Keep two things in mind: - After `guard let self` succeeds, the local strong reference keeps the screen alive while the rest of that run uses it; `weak` decides whether the work starts, not whether it is interrupted. - A capture list can capture something other than `self`, such as `[weak delegate = self.delegate]` or a dependency like `[store]`, which is often better than capturing the whole screen.
- In Swift, does `guard let self` at the top of a long handler let the screen deallocate halfway through?No. Once the guard succeeds, `self` is a strong local reference, so the screen stays alive while the rest of that run uses it. `[weak self]` decides whether the work starts; it does not cancel work already under way. Long jobs that should stop need their own cancellation check.
- In Swift, what is the difference between `[unowned self]` and `[unowned(unsafe) self]`?Plain `unowned`, the same as `unowned(safe)`, checks on every read and stops the program with a fatal error if the object is gone. `unowned(unsafe)` skips that check; a read after deallocation accesses the memory where the object used to be, which is unsafe. It exists for measured performance needs only.
- In Swift, what does `[weak delegate = self.delegate]` capture?It evaluates `self.delegate` when the closure is created and captures that object weakly under the name `delegate`; `self` itself is not captured. Capturing just the dependency the handler needs keeps the screen's lifetime out of the closure entirely.
A courier with a parcel for a hotel guest. [weak self] is asking the front desk whether the guest is still checked in and leaving if not; [unowned self] is walking straight to the room on the assumption they are there, and the delivery fails loudly if they have checked out.
- [unowned self] is a faster [weak self] that also becomes nil.
- [weak self] is required in every closure that mentions self.
- Reading a deallocated unowned reference just returns nil.
- weak captures work on structs and enums as well as classes.
- guard let self else return creates a permanent reference cycle.
Assumes Swift 6.4: implicit self after guard let self arrived in Swift 5.8, and Swift 6 language mode also requires unwrapping a weak self in non-escaping closures.