Junior — Middle
What role does the 'self' keyword play inside closures?
sobes.tech AI
Answer from AI
In Swift, the keyword self inside closures is used to explicitly refer to the current instance of a class or structure, especially when the closure captures self.
This is important to avoid strong reference cycles (retain cycles), which can lead to memory leaks. In closures that capture self, it is common to use a capture list with weak self or unowned self.
Example:
class ViewController {
var name = "Main"
func doSomething() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
guard let self = self else { return }
print(self.name) // here `self` is used explicitly
}
}
}
Here, self inside the closure refers to the current object, and its use helps to avoid confusion with local variables and manage the object's lifecycle.