Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
What is a Capture List in Swift Closures (`[weak self]`)?
junior LevelMost AskedCode ExampleClosures & Scope
In Simple Words: Closures are reference types that strongly capture any variables referenced within their body:
- If a class instance owns a closure (e.g.
onComplete), and the closure referencesself(self.refreshUI()), a Retain Cycle is formed (self -> closure -> self). - Capture List:
[weak self]in the closure declaration instructs the closure to captureselfweakly:
swift
networkManager.fetchData { [weak self] result in
guard let self = self else { return } // Safe unwrapping
self.updateUI(with: result)
}