Unexpected memory leak when using Task in a closure causes

Yes, rarely, but just be aware that there are cases where capturing self weakly is essential. For example, when using a Task with an infinite AsyncSequence. Doing so allows us to break out of the for-await loop when self is deallocated.

Task { [weak self] in
    
    let asyncSequence = NotificationCenter.default.notifications(
        named: UIDevice.orientationDidChangeNotification
    )
    
    for await _ in asyncSequence {
       
        guard let self else {
            // Break out of the loop
            return
        }
        
    }
}
2 Likes