I need to use a weak reference of self inside a closure. I am using the below code for this purpose:
func testFunction() {
self.apiClient.getProducts(onCompletion: { [weak self] (error, searchResult) in
self?.isSearching = false
}
}
Instead of giving the weak reference in the capture list of closure, can I declare a weak reference of self in the body of testFunction.
func testFunction() {
weak var weakSelf = self
self.apiClient.getProducts(onCompletion: {(error, searchResult) in
weakSelf?.isSearching = false
}
}
Similar, syntax was also used in Objective-C to use weak reference inside block.
__weak typeof(self) weakSelf = self;
Is there any advantage of specify the weak reference through the Capture List in closure rather than declaring a weak variable in function body. If there are multiple closures in the function body, it makes more sense to declare a weak variable in function body and use the same variable in all the closures rather than writing as a capture list in each closure.