Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Strong reference cycles with closures


Earlier in this chapter, we said "the best thing is, for the most part, Swift will handle the memory management for us". The "for the most part" section of the quote means that if everything is written in a standard way, Swift will handle the memory management of the closures for us. However, just like classes, there are times where the memory management fails us. Memory management will work correctly for all of the examples that we have seen in this chapter so far. It is possible to create a strong reference cycle that would prevent Swift's memory management from working correctly. Let's look at what happens if we create a strong reference cycle with closures.

A strong reference cycle may happen if we assign a closure to a property of a class instance and within that closure we capture the instance of the class. This capture occurs because we access a property of that particular instance using self like this self.someProperty. By capturing a property...