# Nested weak capture and implicit self in Swift 6

**URL:** <https://forums.swift.org/t/nested-weak-capture-and-implicit-self-in-swift-6/77230>\
**Category:** Using Swift\
**Tags:** concurrency, swift6\
**Created:** [January 16, 2025, 4:21am UTC](https://forums.swift.org/t/nested-weak-capture-and-implicit-self-in-swift-6/77230 "2025-01-16T04:21:12Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Andropov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/andropov/32/35955_2.png) [@Andropov](https://forums.swift.org/u/Andropov)\
**Post date:** [January 16, 2025, 1:30pm UTC](https://forums.swift.org/t/nested-weak-capture-and-implicit-self-in-swift-6/77230/3 "2025-01-16T13:30:15Z")

</div>

In your original version, with two `[weak self]` captures, the following happens when the closure is called:

- **If `self` is `nil` at this point:**

- **If `self` is not nil at this point:**

> [@harlanhaskins](#):
>
> If I remove either the outer `[weak self]` it accepts the code, but I am unsure of the reference capture semantics here (am I good? Is the outer capture not going to retain `self`?)

You probably want to remove the **inner** `[weak self] in`, particularly if the first thing the `Task` is doing is `guard let self else { return }`:

```swift
func acceptsClosure(_ x: @escaping () -> Void) {}

final class A: @unchecked Sendable {
    func nonisolatedMethod() {}

    func createsNestedClosure() {
        acceptsClosure { [weak self] in
            guard let self else { return }
            Task { @MainActor in
                nonisolatedMethod()
            }
        }
    }
}

```

The stored closure will have a weak reference to `self` until it's executed. Then, one of two things happen:

- **If `self` is `nil` at this point:**

- **If `self` is not nil at this point:**

This is usually what you want, because a `Task` should eventually finish, so you're not creating a retain cycle by having a `Task` strongly capture `self`\[1\]. And in this case, the `Task` was already strongly capturing `self` immediately either way.

[This thread](https://forums.swift.org/t/unexpected-memory-leak-when-using-task-in-a-closure-causes/66272) touches on this topic too, it's worth a read.

* * *

1. Key exception: if the `Task` can run forever. For example, by containing a `for await` loop over a never-ending `AsyncSequence`.

---

_[View the full topic](https://forums.swift.org/t/nested-weak-capture-and-implicit-self-in-swift-6/77230)._
