Post

Replies

Boosts

Views

Activity

Reply to Swift 5.5 Task { ... } weak self
Your assumption is correct, the Task will retain the view controller while it's running. The view controller will only be deallocated once the task finishes. This shouldn't be an issue if the task is guaranteed to finish at some point, which is the case if getRowsFromNetwork is internally using the async/await version of the URLSession APIs. If you really don't want to wait until the Task is complete, using weak self as you did solves the issue. You could also capture [rows, tableView] instead of self, which would also allow ViewController to be deallocated as soon as it's dismissed. If you change your mind and decide it's best to cancel the running Task if the view controller is dismissed, you can do so by keeping a reference to the Task, like this: private var task: Task<Void, Error>? func populateRows() { task = Task { ... } } and then cancelling it on deinit: deinit { task?.cancel() }
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’22