# Capturing \`self\` in the body of a \`Task\` started from within a \`deinit\`

**URL:** <https://forums.swift.org/t/capturing-self-in-the-body-of-a-task-started-from-within-a-deinit/61009>\
**Category:** Using Swift\
**Created:** [October 24, 2022, 11:52pm UTC](https://forums.swift.org/t/capturing-self-in-the-body-of-a-task-started-from-within-a-deinit/61009 "2022-10-24T23:52:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [October 24, 2022, 11:52pm UTC](https://forums.swift.org/t/capturing-self-in-the-body-of-a-task-started-from-within-a-deinit/61009/1 "2022-10-24T23:52:00Z")

</div>

i ran into a perplexing memory corruption bug today, which turned out to be because i was referencing `self` from within a `Task` started inside a `deinit`:

```swift
deinit
{
    Task.init
    {
        doSomethingWith(uuid: self.uuid)
        // `self.uuid` contains garbage data
    }
}

```

the problem went away when i copied the property to a local variable:

```swift
deinit
{
    let uuid:UUID = self.uuid
    Task.init
    {
        doSomethingWith(uuid: uuid)
    }
}

```

it makes sense to me why `self` is no longer in an initialized state once the child task begins execution. but why did this ever compile to begin with? why is `self` allowed to escape a `deinit`?

---

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [October 25, 2022, 12:16am UTC](https://forums.swift.org/t/capturing-self-in-the-body-of-a-task-started-from-within-a-deinit/61009/2 "2022-10-25T00:16:28Z")

</div>

> [@taylorswift](#):
>
> why did this ever compile to begin with? why is `self` allowed to escape a `deinit`?

From the last time this was brought up:

> [@Crash in deinit when using Task](https://forums.swift.org/t/crash-in-deinit-when-using-task/55910/2):
>
> This should almost certainly be accompanied by a diagnostic, and Swift is entirely capable of performing that diagnosis (`self` captured by an `@escaping` closure). So I recommend filing a bug report asking for it.

* * *

> [@taylorswift](#):
>
> the problem went away when i copied the property to a local variable

FYI the preferred way to do this is to put the variable in the closure's capture list.

```swift
deinit {
    Task { [uuid] in
        doSomething(with: uuid)
    }
}

```
