iOS Closures in Swift Error Handling and Memory Management Escaping, Weak and Unowned

Gene Bogdanovich
Gene Bogdanovich
11,043 Points

Why we opted out of making fibonacci property weak?

I don’t fully understand why we opted out of making fibonacci property weak to avoid a reference cycle. Can somebody explain in detail please?

1 Answer

Michael Hulet
MOD
Michael Hulet
Treehouse Moderator 46,956 Points

The core issue here is that self retains the fibonacci closure, but by default, the fibonacci closure also retains self since self is referenced within the closure. You're right that one way to break the cycle would've been to make the property itself weak, but that isn't really what we want to do. We want that closure to stay around as long as our object stays around, but that won't happen if we mark it as weak because nothing else references it, so the closure would get deallocated immediately. The best option here (and what Pasan ended up doing) was to make the closure weakly reference self instead. This way, self retains the closure and guarantees it will stay around as long as we want it to, but the closure doesn't also retain self and cause a reference cycle