In Swift, why must a `weak` reference have an optional type, and what did Swift 6.3's `weak let` change about it?
answer
- the object can vanish underneath
- zeroed by ARC, observers silent
- var no longer required
- Sendable classes and weak storage
basics
~20 sARC sets a weak reference to nil when its object is deallocated, so its type must be optional. Weak used to require var; Swift 6.3's weak let (SE-0481) allows an immutable weak property, which a final Sendable class can hold.
solid answer
~40 sA `weak` reference does not keep its object alive, so the object can be deallocated while the reference still exists; ARC then makes the reference read `nil`. That is why the compiler insists on an optional class type ("'weak' variable should have optional type 'Session?'") and why `weak` applies only to class instances. When ARC zeroes it, property observers such as `didSet` are **not** called. Until Swift 6.3 a weak reference also had to be declared `var`, because zeroing was treated as a mutation. SE-0481 (Swift 6.3) allows `weak let`: still optional, still zeroed, but immutable, which lets a `final class` conforming to `Sendable` keep a weak stored property that `weak var` would make it reject as mutable.
code
swift · 12 linesfinal class Session {}
final class Panel {
weak var session: Session? { didSet { print("didSet") } }
}
let panel = Panel()
do {
let s = Session()
panel.session = s // prints "didSet"
} // s is released: session becomes nil, no didSet
print(panel.session == nil) // prints "true"go deeper
Recall that weak references are optional because ARC sets them to nil when the object goes away, and that weak works only with classes.
Explain zeroing: no didSet or willSet, no notification, and why a fresh object stored only in a weak variable is freed at once.
Know the Swift 6.3 change: weak let lets a final Sendable class keep a non-owning reference, while immutable weak captures still need an upcoming-feature flag.
Treat weak let as a small migration aid for Sendable types, not a reason to churn working weak var code across a codebase.
## Why a weak reference is optional In Swift, a **weak reference** is a reference that does not keep its object alive. Strong references decide how long a class instance lives; a weak one only observes it. So the object can be deallocated while a weak property still refers to it, and Swift must answer what that property reads afterwards. The answer is `nil`: **ARC sets a weak reference to `nil`** when the instance it refers to is deallocated. A value that can turn into `nil` must have an **optional type**. The compiler enforces it: ```plaintext error: 'weak' variable should have optional type 'Session?' ``` Because the reference is zeroed rather than left dangling, you never reach a destroyed object through `weak`; reading it gives either the live object or `nil`. ## What zeroing does not do Zeroing is not an ordinary assignment, and that has consequences: - **Property observers are not called.** A `weak var session: Session? { didSet { … } }` runs `didSet` when your code assigns it, but not when ARC sets it to `nil`. Code that relies on `didSet` to notice "the session went away" never hears about it. - **Nothing is notified.** If you need to react to an object's end of life, do it explicitly, for example from that object's own `deinit` or from an event that comes before it. - **A new object assigned only to a weak variable dies at once.** `weak var cache = ImageCache()` compiles with the warning "instance will be immediately deallocated because variable 'cache' is 'weak'": nothing holds the instance strongly. ## Reading a weak reference safely Because a weak reference can become `nil` whenever the last strong reference elsewhere is released, two separate reads of the same weak property are not guaranteed to agree. Bind it once with `if let` or `guard let`: the bound constant is a strong reference for the rest of that scope, so the object cannot go away halfway through the work. Optional chaining such as `session?.refresh()` is fine for a single call, but a sequence of chained calls may see the object for the first and `nil` for the next. ## Rules the compiler enforces 1. `weak` applies only to class instances and class-bound protocol types; on a struct the compiler reports that `weak` may only be applied to class and class-bound protocol types. 2. The type must be optional, as shown above. 3. Before Swift 6.3, the declaration had to be a `var`; the old compiler rejected `weak let` on the grounds that a weak reference may change at run time. ## weak var and weak let **SE-0481**, implemented in **Swift 6.3**, lifts rule 3. The proposal's reasoning is that a weak variable keeps holding the same weak reference; what changes is only whether the program may still observe the object through it. So `weak` can now be combined with `let` wherever `weak var` is allowed, and it must still be optional. | Declaration | Optional? | Reassignable | Allowed in a `final class` conforming to `Sendable` | |---|---|---|---| | `weak var session: Session?` | yes | yes | no: "stored property 'session' of 'Sendable'-conforming class 'Tracker' is mutable" | | `weak let session: Session?` | yes | no | yes, when `Session` is itself `Sendable` (Swift 6.3 and later) | That is the practical gain: a class that must be `Sendable` in Swift 6 language mode can keep a non-owning reference without a wrapper struct or `@unchecked Sendable`. For a local `weak var` that is never reassigned, the Swift 6.4 compiler even nudges you toward it with the warning "weak variable 'w' was never mutated; consider changing to 'let' constant", in the `WeakMutability` diagnostic group. ## Weak captures stay mutable for now SE-0481 also makes an explicit `[weak x]` capture immutable, like every other explicit capture. That part is source-breaking, so in Swift 6.4 it sits behind the upcoming feature `ImmutableWeakCaptures`, which belongs to a future language mode: **Swift 6 mode does not turn it on**. Passing `-enable-upcoming-feature ImmutableWeakCaptures` makes `c = nil` inside such a closure fail with "cannot assign to value: 'c' is an immutable capture". How capture lists work in general is covered in the Swift material on closures. ## Summary - Optional, because ARC zeroes the reference when the object is deallocated. - Zeroing skips `didSet` and `willSet`. - `weak let` exists since Swift 6.3 and helps `Sendable` classes. - Immutable weak captures need an explicit upcoming-feature flag in Swift 6.4.
- In Swift 6 language mode, is a `[weak self]` capture immutable now?Not by default. SE-0481 makes explicit weak captures immutable, but because that breaks existing code, Swift 6.4 keeps it behind the upcoming feature `ImmutableWeakCaptures`, which belongs to a future mode and is off in Swift 6 mode. With `-enable-upcoming-feature ImmutableWeakCaptures`, assigning to the capture fails with "cannot assign to value: 'c' is an immutable capture".
- Why does Swift warn about `weak var cache = ImageCache()`?Nothing holds the new instance strongly, and a weak reference does not keep it alive, so ARC releases it immediately and `cache` reads `nil` on the next line. Swift warns "instance will be immediately deallocated because variable 'cache' is 'weak'". Give the object a strong owner and make only the back-reference weak.
- A weak property's didSet runs when ARC sets it to nil.
- weak can be applied to a struct property to avoid copying it.
- Swift 6 language mode makes every [weak self] capture immutable.
- A weak reference can dangle and crash the way unowned does.
- weak var x = MyClass() keeps the new object alive while x is in scope.
Assumes Swift 6.4; weak let arrived in Swift 6.3 (SE-0481), while immutable weak captures stay behind the upcoming feature ImmutableWeakCaptures, which Swift 6 mode does not enable.