Reference cycles for closures

You’ve learned in Chapter 10, “Collection Iteration with Closures” that closures capture values from the enclosing scope. You create a reference cycle if you assign a closure which captures a class instance to a property, since closures are reference types under the hood.

For example, add a property that computes the tutorial’s description to the Tutorial

class like this:

lazy var tutorialDescription: () -> String = { return "(self.title) (self.category)"

}

Recall from Chapter 12, “Properties” that you define a lazy property to ensure you don’t assign it until you use it for the very first time, and that self is only available after initialization.

Now print the tutorial’s description to the console. Add the following code right after the tutorial object’s declaration:

print(tutorial!.tutorialDescription())

You’ve created another strong reference cycle between the tutorial object and the closure by capturing self, so only the author’s deinit method runs. In order to break it, you need to know a thing or two about capture lists.

Note: Swift requires you use self inside closures, as a reminder that a reference to the current object is being captured. The only exception to this rule is in the case of non escaping closures, which you’ll learn about just a bit later.

results matching ""

    No results matching ""