Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Gene Bogdanovich
Gene Bogdanovich
14,618 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
Michael Hulet
47,912 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