Thumbnail for You're likely using [weak self] incorrectly in your Swift Tasks... #concurrency #swift #ios by donny wals

You're likely using [weak self] incorrectly in your Swift Tasks... #concurrency #swift #ios

donny wals

56s184 words~1 min read
YouTube auto captions
Transcript source

YouTube auto captions

This transcript was extracted from YouTube's auto-generated caption track. The transcript below is server-rendered so it can be read, searched, cited, and shared without opening the original YouTube player.

Pull quotes
[0:01]We have a weak self capture inside of the task, and we immediately make that capture strong again.
[0:01]Tasks can swift concurrency start running as soon as possible, which in practice is pretty much immediately.
[0:01]So that means that self hasn't gone away at the point that this task would start.
[0:01]So that guard is pretty much always going to allow us to have a strong capture of self.
Use this transcript
Related transcript hubs

[0:01]It might not be obvious, but the code below has a memory leak. We have a weak self capture inside of the task, and we immediately make that capture strong again. Tasks can swift concurrency start running as soon as possible, which in practice is pretty much immediately. So that means that self hasn't gone away at the point that this task would start. So that guard is pretty much always going to allow us to have a strong capture of self. In the while loop, we make use of self by fetching more pages, and we keep going as long as there are more pages available. This means that for the duration of the while loop, self cannot go away. If we do want self to be able to be deallocated, we need to make sure we don't have a strong reference at the start of our task. We can unwrap self inside of the while loop instead, making every iteration have its own strong reference to self. This solves the leak and avoids one of the common issues I see in tasks.

Need another transcript?

Paste any YouTube URL to get a clean transcript in seconds.

Get a Transcript