Weak self, a story about memory management and closure in Swift
['Benoit Pasquier']
Benoit Pasquier - Swift, Data and more
Right off the bat, we can see self is strongly captured in the first and second closures: the closures keep a strong reference to self which internally increment the reference counter and can prevent to de-allocate the instance during the execution of doSomething . () } var didSomething : Bool = false var didSomethingElse : Bool = false deinit { print ( "Deinit" ) } func printCounter () { print ( CFGetRetainCount ( self )) } func doEverything () { print ( "start" ) printCounter () self . var didSomething : Bool = false var didSomethingElse : Bool = false deinit { print ( "Deinit" ) } func printCounter () { print ( CFGetRetainCount ( self )) } func doEverything () { print ( "start" ) printCounter () doSomething = { [ weak self ] in guard let self = self else { return } self .