Nested closures & weak capture
January 27th, 2016
In Swift code, there’s a potential strong reference leak hiding in nested closures:
foo({
bar({ [weak self] in
self?.baz()
})
})
This code seems okay, since only bar
refers to self
, which is captured weakly. However, that’s not actually the case! foo
captures self
strongly. Instead:
foo({ [weak self] in
bar({ [weak self] in
self?.baz()
})
})
Will work correctly. There is a proposal to change this.