Closures Are Reference Types

Closures are reference types. This means that when you assign a function to a constant or variable, you are actually setting that constant or variable to point to the function. You are not creating a distinct copy of that function. One important consequence of this fact is that any information captured by the function’s scope will be changed if you call the function via a new constant or variable.

To see this, create a new constant and set it equal to your growBy(_:) function.

Listing 13.13 Duplicate growth

... func makePopulationTracker(forInitialPopulation population: Int) -> (Int) -> Int { var totalPopulation = population func populationTracker(growth: Int) -> Int { totalPopulation += growth return ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.