Michael Long
Sep 17, 2024

--

Points...

"Closures don't have to be executed immediately or upon completion. Like any function, a closure has its own lifecycle, and capturing self weakly is the only way to prevent a retain cycle."

There's a difference between closure captures that retain references and retain cycles. If a closure captures self and is stored in that object, then you have a retain cycle and weak/unowned is needed to break it.

If you pass a callback closure to, say, datatask, and that closure captures self, then the closure retains the reference... and then frees it once the closure completes. There is no cycle.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (1)