Don’t you just love crashes that only present on a customer’s machine, and not yours? Yes, me neither. Although, as it turns out, that’s not exactly what happened – it just looked like it.
Let’s take a look at this code of a subclass of NSView:

Looks quite ordinary, right? There’s a closure changeToolBlock, which I can call within func keyDown(with:) for different conditions.
While the [weak self] capture is not necessary because the closure never leaves the scope of the function, it’s still valid code.
And it does run – if you’re in the Debug build configuration. Once you compile the Release build, the code gets optimized, and something odd occurs that causes the app to crash:

Now, why would it crash there? There should only be two logical values for self:
1) self exists because the view is still part of the window, thus guard let self passes and the code continues to run
2) self no longer exists because the view was removed from the window and deallocated. But even then, guard let self should find that self no longer exists, and return.
But what actually happens is neither: the app crashes.
What makes this even weirder is that certain code changes, which seemingly have nothing to do with this, fix the crash all of a sudden.
If I remove aLocalVar = false from the closure, the code runs fine!
Or if I call changeToolBlock in DispatchQueue.main.async{...} or in Task { @MainActor in ...}, the code runs fine!
This is where it dawned on me that I might have a Swift compiler bug on my hands.
To reiterate, I realize that [weak self] is completely unnecessary here. The reason I had it in there in the first place was because initially, I would call the closure in different Tasks, but then refactored and forgot about the [weak self], or figured: “won’t hurt” (I stand corrected). But it is valid code. It should run just fine. Yet it doesn’t.
So I turned to the disassembly for what’s going on. Now bear with me, please – I don’t “speak” (dis-)assembly, but from the comments Xcode prints, I think I get the picture.

Of particular interest are the lines 10, 18, 26 and 27.Line 10: symbol stub for: swift_unknownObjectWeakInit
This must be the [weak self] we’ve been hearing so much about, getting created.Line 18: symbol stub for: swift_unknownObjectWeakDestroy
It looks like the weak reference is destroyed here, before the closure is called. Why!?Line 26: function signature specialization …
This is our closure getting called, after weak self was destroyed.
Inside the closure, this happens:

Look at line 12:symbol stub for: swift_unknownObjectWeakLoadStrong
It’s looking for that weak self, can’t find it in the weak references table1, and thus – KABOOM – it crashes.
It’s like Bambi looking for his mama. But mama ain’t coming.
So what is actually going on here?
Note: the following is the gist of a conversation I had with multiple AIs about this, because “sub”, “stp”, “add”, “mov” and “bl” mean nothing to me. I also let them analyze the SIL (“Swift Intermediate Language”) and disassembly.
The closure never outlives the function it was created in, so the compiler can keep it on the stack (the current thread’s execution storage), rather than allocating it on the heap (dynamically allocated memory).
When the compiler runs, it sees that the closure captures and mutates var aLocalVar, and explicitly captures weak self.
Because a local variable is involved and mutated in a closure, Swift’s rule is that the variable and weak self must each live in a “box”, memory on the heap.
Since the closure is non-escaping, optimization in the form of AllocBoxToStack comes into play, promoting those boxes back to the Stack (see Line 26 above again, “Arg[1/2] = Stack Promoted from Box”).
It then analyzes the lifetime of the boxes. It sees aLocalVar is declared in the outer scope of the closure (in func keyDown) and correctly extends its lifetime until the function exits. However, it miscalculates the lifetime for weak self and destroys it immediately. It appears that its liveness scan (how long weak self is in use) looks only for direct uses of it in the outer function, but fails to realize that calling the closure later in that function is still using it.
Why it works without capturing and mutating a local variable inside the closure? Because then no Heap box is involved at all, because nothing gets mutated. weak self is captured as an immutable value, the weak reference stored directly in the closure’s context, and the optimization step AllocBoxToStack never even runs on it.
Why it works when calling the closure in a Task or a DispatchQueue afterwards? Because then the closure becomes escaping (it escapes the current Stack), and the compiler is not allowed to run AllocBoxToStack, either.
I run my own apps almost exclusively from Xcode (Build and Run), so if something weird happens, I have it right there in the debugger. But that was my problem. I was in the Debug build configuration, which omits any optimizations. Only switching to the Release build configuration allowed me to reproduce the crash. Don’t ask me how long it took me to finally try that. Just… don’t.
Of course, the solution is painfully easy. Remove the admittedly unnecessary [weak self], along with the guard check, and move on with your life. But it still irks me, so I’ve filed a bug (FB25693835) on the Swift compiler.
I guess I’ll test more thoroughly in the “Release” build configuration from now on!
Addendum
The unoptimized SIL, commented by AI (Gemini 3.8 Flash Medium), created by AI with Xcode 27.2, swift-driver version: 1.168.6 Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1), Target: arm64-apple-macosx27.2.0:
// 1. Allocate heap boxes for `aLocalVar` and `[weak self]`
%4 = alloc_box ${ var Bool }, var, name "aLocalVar"
%12 = alloc_box ${ var @sil_weak Optional<MyView> }
// 2. Initialize the weak reference in the heap box
%14 = project_box %13, 0
store_weak %16 to [init] %14
// 3. Build the closure (`partial_apply`), capturing the boxes
%23 = partial_apply %closure(%20, %21)
%24 = move_value %23 // changeToolBlock
// 4. Release caller's initialization handle to the weak box
destroy_value %12
// 5. Call the closure (the closure still retains the heap box!)
%37 = apply %36(%35) : $@callee_guaranteed (@guaranteed String) -> ()
// 6. Cleanup at the very end of keyDown
destroy_value %24 // release closure
destroy_value %4 // release aLocalVar box
The optimized SIL:
sil private [thunk] @MyView.keyDown(with:) : $@convention(objc_method) (NSEvent, MyView) -> () {
bb0(%0 : $NSEvent, %1 : $MyView):
// 1. Stack allocations instead of heap boxes:
%3 = alloc_stack [var_decl] $Bool, var, name "aLocalVar"
%7 = alloc_stack [lexical] $@sil_weak Optional<MyView>
// 2. Initialize weak self on the stack:
%8 = enum $Optional<MyView>, #Optional.some!enumelt, %1
store_weak %8 to [init] %7
// 💥 3. THE FATAL BUG: AllocBoxToStack destroys and frees %7 immediately!
destroy_addr %7 // <-- Destroys the weak reference!
dealloc_stack %7 // <-- Frees stack slot %7!
// 4. Set up the argument string "mytest":
%21 = struct $String (...)
// 💥 5. Invokes the closure, passing the ALREADY DEALLOCATED %7 stack address:
%22 = apply %13(%21, %7, %3) : $@convention(thin) (@guaranteed String,
@inout_aliasable @sil_weak Optional<MyView>,
@inout_aliasable Bool) -> ()
// 6. aLocalVar stack slot %3 is properly kept alive until here:
dealloc_stack %3
return %26
}
And inside the closure:
sil private @specialized closure #1 in MyView.keyDown(with:) : ... {
bb0(%0 : $String, %1 : $*@sil_weak Optional<MyView>, %2 : $*Bool):
// Line 41: guard let self else { return }
%6 = load_weak %1 // 💥 Tries to read from deallocated %7!
switch_enum %6, case #Optional.some: bb1, case #Optional.none: bb2
...
- Logged in the Console:
Weak reference loaded from 0x16f2c2810 contains 0xfad00749cbd0500 which is not in the weak references table↩︎