Force-unwrapping weak references can turn normal lifetime changes into application crashes
Source references: 3The document acknowledges that a weak reference may legitimately become nil after its strong owner's last use, but then calls optional binding “worse” than force-unwrapping. If an agent uses this to replace safe nil handling with `!`, normal deallocation will cause a runtime trap.
The affected process can crash immediately. If requests, UI events, or external input can repeatedly reach that path, this can cause denial of service or loss of unsaved work.
This is active coding guidance, not a warning, negated example, or test. It acknowledges that a `weak` reference may legitimately become `nil` after normal object release, but then says optional binding is worse than force-unwrapping. If an agent follows that advice and replaces safe nil handling with `!`, release before the read will cause a runtime crash, potentially interrupting work or leaving data unsaved. A user can require explicit nil handling, allowing force-unwrapping only where a strong lifetime guarantee is proven.
- **An object's guaranteed lifetime ends at its last use, not at the closing brace.** Observed lifetimes are an emergent property of the optimizer and _will_ change. Code that depends on when a `deinit` runs is a latent bug.- **`weak`/`unowned` are for breaking reference cycles — nothing else.** Reading a `weak` reference after the strong owner's last use may legitimately give `nil`. Optional binding there is _worse_ than force-unwrap: it turns a loud crash into a silent wrong answer.Show 2 other places
- **An object's guaranteed lifetime ends at its last use, not at the closing brace.** Observed lifetimes are an emergent property of the optimizer and _will_ change. Code that depends on when a `deinit` runs is a latent bug.- **`weak`/`unowned` are for breaking reference cycles — nothing else.** Reading a `weak` reference after the strong owner's last use may legitimately give `nil`. Optional binding there is _worse_ than force-unwrap: it turns a loud crash into a silent wrong answer.- **Better than `weak`: don't build the cycle.** Factor the shared data into a third type both sides reference, turning the cycle into a tree.- **Better than `weak`: don't build the cycle.** Factor the shared data into a third type both sides reference, turning the cycle into a tree.- **Next best: redesign the API** so the object is only reachable through a strong reference. `withExtendedLifetime` works but shifts correctness onto you and spreads through a codebase — treat it as a patch, not a design.- **Keep `deinit` side effects local.** Publishing metrics or firing a global effect from `deinit` sequences against optimizer decisions. Use `defer` at the call site instead, and leave `deinit` for verification.