4 ms·
I know the article is about JavaScript, but I was wondering how Swift resolves the problem of weak self within the async/await model. If the part of the functi
by mojuba 5y ago
I know the article is about JavaScript, but I was wondering how Swift resolves the problem of weak self within the async/await model.
If the part of the function after await is the callback, how do I specify weak self if I need to?
- ninkendo 5y agoYou can generally do something like: Task { [weak self] in await foo() self?.bar() // self may be nil } That is, you can just make a new task which awaits on something and then does more work, and that Task can be tagged with weak self so that self can be freed.
- mojuba 5y agoSo basically no way to do the same with await, other than of course declaring a weak local var.
- ninkendo 5y agoIf you’re await’ing a variable directly in the same scope, of course self will be retained, you’re still running inside self’s scope. I guess I’m confused by the question… if you want to await something and allow self to be freed in the process, you can use Task{ [weak self] } and then return early. If you don’t want to return early, you can’t really release self yet, since the scope shouldn’t outlive self.